I have a function called workForThread, that takes two arguments, and returns void. I would like to thread this function using something like:
thread(workForThread,a,b);
Where a
and b
are of the appropriate types. The above code does not compile, giving a "too many arguments for call" error ("error C2197: 'void (__cdecl *)(char *)' : too many arguments for call")
How can I resolve this?
Note: I have looked at these two questions, but the resolutions that work there do not seem to work for me. Additionally, I have a feeling there is a way to do it built into c++11, and that is what I am looking for.
In C++11, the way to do it is more or less the way you have attempted:
std::thread myThread(workForThread,a,b);
provided workForThread is a (non-member) function that takes those two parameters.
When using C++11 you could use a lambda function which may use (non-formal) parameter of the context. "Capturing"
Something like
void doIt (int a, int b) { // do something, your workForThread
}
..
int a = 1;
int b = 2;
std:thread r ([=](){doIt (a, b); return 1;});
When only calling a single function juanchopanza answer may be somewhat more efficient since no new function will be created.
The lambda version allows you to configure more. Let say you are starting threads which calls in the end 2 functions out of 3. juanchopanza approach would require NAMED functions for each permutation.
At the moment I consider the difference of both approaches to be mostly a matter of taste.
When you like to read more about lambda functions
What is a lambda expression in C++11?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With