I'm trying to learn the basics of threads, mutex and function objects.
Here's my test code trying to output "Hello" and "World" by two different threads every second.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
mutex m;
struct Hello {
public:
void operator()(){
for(int i = 0; i < 10; i++) {
this_thread::sleep_for(chrono::milliseconds{1000});
unique_lock<mutex> lock {m};
cout << "Hello ";
}
}
};
struct World {
public:
void operator()(){
for (int i = 0; i < 10; i++) {
this_thread::sleep_for(chrono::milliseconds{1000});
unique_lock<mutex> lock {m};
cout << "World!" << "\n";
}
}
};
/*
*
*/
int main(int argc, char** argv) {
thread t1 {Hello()};
thread t2 {World()};
t1.join();
t2.join();
return 0;
}
|
My code doesn't compile.
Here's my compiler version:
g++ (Ubuntu 7.4.0-1ubuntu1~18.04) 7.4.0
using "-g -std=c++14" argument I get the following error:
g++ -o dist/Debug/GNU-Linux/01 build/Debug/GNU-Linux/main.o
build/Debug/GNU-Linux/main.o: In function `std::thread::thread<Hello>(Hello&&)':
/usr/include/c++/7/thread:122: undefined reference to `pthread_create'
build/Debug/GNU-Linux/main.o: In function `std::thread::thread<World>(World&&)':
/usr/include/c++/7/thread:122: undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
If that's of relevance, I'm using NetBeans IDE 11.0 on an Ubuntu 18.04.
Thanks!