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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With