Answer the question
In order to leave comments, you need to log in
How to pass an argument to a C++ Thread?
POSIX Thread has a pthread_create function that is passed a pointer to a function and arguments to that function.
How does this happen in C++ Thread?
I have a vector. vector<thread> threads;
I need to pass a function and parameters in a loop, something like this:
for (int i = 0; i < NUM_THREAD; i++)
{
threads.push_back(std::thread(func, (void*)param));
}
Answer the question
In order to leave comments, you need to log in
std::vector<std::thread> thread_pool;
void foo(int i) {
// do...
}
int main() {
thread_pool.push_back(std::thread(foo, 5));
return 0;
}
You can also create a thread like this
std::thread([] {
// your code here
});
And even so
std::thread([param] { // capture by value
foo(param);
});
The types of parameters passed to the std::thread constructor must be compatible with the types of parameters that func takes. In addition, the problem may not be in the parameter, but in an attempt to copy std::thread into a vector (try wrapping it in std::move). You should see for yourself and write here how exactly the compiler swears.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question