Reputation: 3478
I'm asking about the <thread>
library in C++11 standard.
Say you have a function like:
void func1(int a, int b, ObjA c, ObjB d){
//blahblah implementation
}
int main(int argc, char* argv[]){
std::thread(func1, /*what do do here??*/);
}
How do you pass in all of those arguments into the std::thread
? I tried listing the arguments like:
std::thread(func1, a,b,c,d);
But it complains that there's no such constructor. One way to get around this is defining a struct to package the arguments, but is there another way to do this?
Upvotes: 90
Views: 194025
Reputation: 535
Had the same problem. I was passing a non-const reference of custom class and the constructor complained (some tuple template errors). Replaced the reference with pointer and it worked.
The reference must point to a copy-constructable object (copied when passing between threads) or use std::ref(yourParam)
to explicitly request a shared reference.
Upvotes: 19
Reputation: 770
In my case I just changed the function name and error gone.
Before:
thread(merge, first_item, mid_item, last_item).join();
After: thread(doMerge, first_item, mid_item, last_item).join();
And error gone. Yes it's freaking!!
Upvotes: 0
Reputation: 121
If your error message says
error: no matching constructor for initialization of 'std::thread'
then it's likely because you forgot to specify the C++ standard to be 11. For g++ compiler:
g++ std=c++11 main.cpp -o main
Upvotes: 0
Reputation: 18751
You literally just pass them in std::thread(func1,a,b,c,d);
that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminate
is called. You could std::join
or std::detach
it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach
.
This is how it should be done.
std::thread t(func1,a,b,c,d);
t.join();
You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.
Upvotes: 97
Reputation: 1517
If you're getting this, you may have forgotten to put #include <thread>
at the beginning of your file. OP's signature seems like it should work.
Upvotes: -3