Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problems using threads in C++ on windows 10 (using g++ as compiler)

I'm trying to create a thread and make it print something to the terminal. I was having some problems so I decided to take this very simple piece of code someone else made, when I compile it I get the errors listed below, but other people online seem to have no problem running this.

#include <iostream>
#include <thread>

using namespace std;

void hello_world()
{
    cout << "Hello from thread!\n";
}

int main()
{
    thread threadobj1(hello_world);
    threadobj1.join();
    return 0;
}

The compiler (mingw32-gcc-g++-bin 8.2.0.3 on windows 10) gives the following errors:

.\multiT.cpp: In function 'int main()':
.\multiT.cpp:13:5: error: 'thread' was not declared in this scope
     thread threadobj1(hello_world);
     ^~~~~~
.\multiT.cpp:13:5: note: 'std::thread' is defined in header '<thread>'; did you forget to '#include <thread>'?.\multiT.cpp:3:1:
+#include <thread>

.\multiT.cpp:13:5:
     thread threadobj1(hello_world);
     ^~~~~~
.\multiT.cpp:14:5: error: 'threadobj1' was not declared in this scope
     threadobj1.join();
     ^~~~~~~~~~
.\multiT.cpp:14:5: note: suggested alternative: 'thread_local'
     threadobj1.join();
     ^~~~~~~~~~
     thread_local

I was hoping someone might be able to help me figure out why this isn't working for me, the error says I should include , but I've clearly already done that so I'm a bit lost now. I've already tried to install the "mingw32-pthreads-w32-dev" packages as those weren't installed but that hasn't made any difference. I've also added the following arguments to the compiler:

g++ -std=c++14 -pthread .\multiT.cpp
like image 910
Matt Avatar asked May 11 '19 17:05

Matt


1 Answers

For anyone else dealing with this problem: The simplest solution is to download mingw-64 and use their compiler instead.

Then use the -std=gnu++11 or -std=c++11 arguments to enable support for the ISO C++ 2011 standard and by extension support for threads (do note: This support is currently experimental, though that has not given me any problems so far).

like image 154
Matt Avatar answered Nov 07 '22 19:11

Matt