Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass multiple arguments into std::thread

I'm asking 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 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?

like image 542
turtlesoup Avatar asked Dec 03 '13 00:12

turtlesoup


People also ask

How do you pass more than one parameter in a thread?

if you declare parameter to be an array of int ("int parameter[2];"), then you can pass parameter as a pointer. It is the pointer to first int. You can then access it from the thread as an array.

Can you pass arguments to a thread?

You can only pass a single argument to the function that you are calling in the new thread.

Can you pass a reference to a thread C++?

In c++11 to pass a referenceto a thread, we have std::ref(). std::thread t3(fun3, std::ref(x)); In this statement we are passing reference of x to thread t3 because fun3() takes int reference as a parameter. If we try to pass 'x' or '&x' it will throw a compile time error.

How do you declare a thread in C++?

To start a thread we simply need to create a new thread object and pass the executing code to be called (i.e, a callable object) into the constructor of the object. Once the object is created a new thread is launched which will execute the code specified in callable. After defining callable, pass it to the constructor.


1 Answers

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.

like image 83
aaronman Avatar answered Sep 24 '22 17:09

aaronman