Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

multithreading - Why doesn't my compiler recognize #include <thread> (c++)?

I wrote this as a simplified version of a multithreading example to get a feel for it, but am running into some issues when compiling. My compiler says that thread is not a member of std and prompts me to add #include <thread> to my code even though I have already done so. I've been unable to find any similar problems so far, but I suspect that it is an issue with how I'm compiling it because my code is very similar to the example code.

#include <iostream>
#include <thread>

void doWork () {
    std::cout << "Working...
";
}

int main () {
    std::thread worker(doWork);
    
    work.join();
    std::cout << "Finished
";
    
    return 0;
}

My compiler is MinGW g++ 9.2.0
I compiled with g++ main.cpp -o main and it gave me these errors:

main.cpp: In function 'int main()':
main.cpp:9:7: error: 'thread' is not a member of 'std'
    9 |  std::thread worker(doWork);
      |       ^~~~~~
main.cpp:3:1: note: 'std::thread' is defined in header '<thread>'; did you forget to '#include <thread>'?
    2 | #include <thread>
  +++ |+#include <thread>
    3 |
main.cpp:11:2: error: 'work' was not declared in this scope
   11 |  work.join();
      |  ^~~~
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

MinGW-w64 by default comes with native (Win32) instead of POSIX threads support, and unfortunately there is currently no Win32 gthreads implementation (the threading subsystem of libstdc++), hence no threading functionality in GCC.

You need to switch from x86_64-w64-mingw32-g++-win32 to x86_64-w64-mingw32-g++-posix package to get std::thread working in MinGW-w64.

The question mingw-w64 threads: posix vs win32 discusses this issue in more detail.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...