Passing multiple arguments to a threaded function

13,358

Solution 1

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?

Solution 2

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.

Share:
13,358
soandos
Author by

soandos

Student. Third to earn the marshal badge on SuperUser profile for soandos on Stack Exchange, a network of free, community-driven Q&A sites http://stackexchange.com/users/flair/375094.png profile for soandos on Project Euler, which exists to encourage, challenge, and develop the skills and enjoyment of anyone with an interest in the fascinating world of mathematics. http://projecteuler.net/profile/soandos.png

Updated on July 05, 2022

Comments

  • soandos
    soandos almost 2 years

    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.