Windows 下无法使用 C++11 标准 thread 类

2023-07-11,,

问题描述

最近需要在 windows 平台使用 C++ 多线程编程,编译时提示错误 thread is not a member of std, or you maybe forget '#include <thread>'

下面是出现此问题的环境背景:

    已经添加 thread 头文件
    编译时已添加 -pthread 参数
    MinGW 版本为 (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0,支持多线程

解决方法

导致这个问题的原因是 MinGW GCC 缺少 C++11 标准的线程类实现,需要从 github 下载相关的头文件,重新编译即可使用线程库。

下载地址:meganz/mingw-std-threads

将上述头文件下载完成后放入本地 MinGW 环境中,我的路径是:./mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/

使用方法

#include <iostream>
#include <mingw.thread.h> void read() {
std::cout << "Success!" << std::endl;
} int main(int argc, char* argv[]) {
std::thread th(read);
}

编译命令:g++ main.cpp -o main -pthread -std=c++11

执行:./main.exe

参考文章

[1] C++11 thread类在windows上无法使用。std 没有成员 thread、thread not member of std

Windows 下无法使用 C++11 标准 thread 类的相关教程结束。

《Windows 下无法使用 C++11 标准 thread 类.doc》

下载本文的Word格式文档,以方便收藏与打印。