Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing multiple arguments to a threaded function

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.

like image 328
soandos Avatar asked May 07 '12 18:05

soandos


2 Answers

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.

like image 85
juanchopanza Avatar answered Sep 22 '22 12:09

juanchopanza


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?

like image 21
stefan bachert Avatar answered Sep 22 '22 12:09

stefan bachert