user3376098
user3376098

Reputation: 39

Any way to pass parameters to functions in a thread?

Example:

std::thread t1(function(8, 9));

This doesn't work for me. Perhaps there's a way to do that. Thanks in advance.

Upvotes: 0

Views: 63

Answers (1)

Filip Roséen
Filip Roséen

Reputation: 63797

std::thread t1 (function (8, 9));

In the above snippet we would initialize t1 with the returned value of function(8,9) which, as you have stated, isn't what you are looking for.


Instead you can make use of the constructor of std::thread defined to take a callable object as its first parameter, and than the parameter(s) that should be passed to it when invoking it.

std::thread t1 (function, 8, 9);

See this simple example:

#include <iostream>
#include <thread>

void func (int a, float b) {
  std::cout << "a: " << a << "\n";
  std::cout << "b: " << b << "\n";
}

int main () {
  std::thread t1 (func, 123, 3.14f);

  t1.join ();
}

a: 123
b: 3.14

Upvotes: 5

Related Questions