7

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.

Community
  • 1
  • 1
soandos
  • 4,699
  • 12
  • 56
  • 89

2 Answers2

13

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.

juanchopanza
  • 210,243
  • 27
  • 363
  • 452
7

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?

Community
  • 1
  • 1
stefan bachert
  • 8,643
  • 3
  • 31
  • 38