Temple
Temple

Reputation: 1631

How to start thread with function object with argument

I code snipped below:

#include <iostream>
#include <thread>


class Me{
public:
bool isLearning;
 void operator()(bool startLearning){
  isLearning = startLearning;
 }
};

int main(){
Me m;
std::thread t1(m(true));
t1.join();
std::cout << m.isLearning << std::endl;
}

I can't start thread with callable object when argument is passed, is there any way to start thread and pass callable object with argument in thread constructor?

Upvotes: 3

Views: 883

Answers (2)

Mohamad Elghawi
Mohamad Elghawi

Reputation: 2124

Problem #1

std::thread t1(m(true)); does not do what you think it does.

In this case you are invoking your function object and passing it's result (which is void) to the constructor of std::thread.

Solution

Try passing your function object and arguments like this:

std::thread(m, true);

Problem #2

std::thread will take a copy of your function object so the one it uses and modifies will not be the same one declared in main.

Solution

Try passing a reference to m instead by using std::ref.

std::thread(std::ref(m), true);

Upvotes: 9

n. m. could be an AI
n. m. could be an AI

Reputation: 119877

std::thread t1(m, true);

Bear in mind that, absent proper synchronisation,

isLearning = startLearning;

and

std::cout << m.isLearning << std::endl;

executing simultaneously constitute a data race and undefined behaviour.

Don't forget to t1.join() in the end.

Upvotes: 0

Related Questions