Pass multiple arguments into std::thread

C++MultithreadingC++11

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

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.

Solution 3 - C++

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.

Solution 4 - C++

On Mac I tried this and it works:

#include <iostream>
#include <thread>

using namespace std;

string t1(int firstInput, int secondInput){
    cout << firstInput << " ,";
    cout << secondInput << " ,";

    return "finish thread t1";
}


int main()
    {   
        int userInput1;
        int userInput2;
        cout << "Set a number" << endl; 
        cin >> userInput1;
        cout << "Set second number"<< endl;
        cin >> userInput2;
        thread ThreadT1(t1, userInput1, userInput2 );
        ThreadT1.join();

    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionturtlesoupView Question on Stackoverflow
Solution 1 - C++aaronmanView Answer on Stackoverflow
Solution 2 - C++JiříView Answer on Stackoverflow
Solution 3 - C++pixelpaxView Answer on Stackoverflow
Solution 4 - C++sq.ashkanView Answer on Stackoverflow