[c++] 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?

This question is related to c++ multithreading c++11

The answer is


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.


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.


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to multithreading

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Waiting until the task finishes What is the difference between Task.Run() and Task.Factory.StartNew() Why is setState in reactjs Async instead of Sync? What exactly is std::atomic? Calling async method on button click WAITING at sun.misc.Unsafe.park(Native Method) How to use background thread in swift? What is the use of static synchronized method in java? Locking pattern for proper use of .NET MemoryCache

Examples related to c++11

Remove from the beginning of std::vector Converting std::__cxx11::string to std::string What exactly is std::atomic? C++ How do I convert a std::chrono::time_point to long and back Passing capturing lambda as function pointer undefined reference to 'std::cout' Is it possible to use std::string in a constexpr? How does #include <bits/stdc++.h> work in C++? error::make_unique is not a member of ‘std’ no match for ‘operator<<’ in ‘std::operator