The following is my 1st multi-threaded program. But while it was compiled, there is a linking error. The part of the error message:
std::thread::thread<void (&)(int), int&>(void (&)(int), int&):
test.cpp (.text._ZNSt6threadC2IRFviEJRiEEEOT_DpOT0_[_ZNSt6threadC5IRFviEJRiEEEOT_DpOT0_]+0x33): undefined reference pthread_create
collect2: error ld return 1
#include<thread>
void f(int i) {}
int main() {
std::thread t(f, 1);
t.join();
return 0;
}
You need to compile with
-pthread
as a compile option.I got your code to compile with this (though I added the
-Wall
function to give me all warning notices):(where
foo.cpp
was the input filename I used containing your code)Even if your program uses c++11's threading feature, you need to specify '-pthread' to successfully compile your program.
Please read below thread for more info https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=763369
I had fixed the same Issue (undefined reference to Pthread_create) So the issue is not your Code but the argument which be have missed while generating object file in G++ compiler
Here is the issue:
This is how I fixed it:
you can take a look at this example:
https://mockstacks.com/Cpp_Threading
#include #include #include
using namespace std;
// The function we want to execute on the new thread. void task1(string msg) { cout << "task1 says: " << msg; }
int main() { // Constructs the new thread and runs it. Does not block execution. thread t1(task1, "Hello");
// Do other things...
// Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution. t1.join(); }