Thread Function with Arguments

  • We can pass arguments to the entry point function
  • We list them as extra arguments to the constructor
void hello(std::string);

std::thread thr(hello, "Hello thread!");
  • The std::thread object owns the arguments

    • lvalue arguments are passed by value
    • rvalue arguments are passed by move
  • To pass by move, we must provide an rvalue

    • The argument must have a move constructor

Thread Function with Pass by Move

void func(std::string&&);

std::string str = "abc";

std::thread thr(func, std::move(str));

Thread Function with Reference Argument

  • Use a reference wrapper
    • Wrap the argument in a call to std::ref()
void hello(std::string&);

std::string str = "abc";

std::thread thr(hello, std::ref(str));
  • Use std::cref() for a const reference
  • Beware of dangling references!

Member Function as Entry Point

  • We can use a member function as the entry point
  • Requires an object of the class
class greeter {
public:
  void hello();
};

greeter greet;

// Pass a pointer to the member function and a pointer to the object
std::thread thr(&greeter::hello, &greet);

Lambda Expression as Entry Point

int i = 3;

// Capture by reference
std::thread thr([&i] {
  i *= 2;
});

Lambda Expression with Arguments

std::thread thr([] (int i1, int i2) {
  std::cout << i1 + i2 << '\n';
}, 2, 3);