3

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?

2 Answers 2

9

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);

Sign up to request clarification or add additional context in comments.

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.