Reputation: 19
I have a function (messageArrived) that call's a function (setAnimation) inside a new thread. How can i access a boolean that is defined inside the messageArrived function and access it in the second thread?
If there is a new message i want to terminate the second thread (setAnimation). I fugured that whit a boolean is the only way to "terminate" a thread.
#include <thread>
bool start = false;
void setAnimation(std::string msg){
start = true;
while(start){
//do something
}
return;
}
int messageArrived(std::string message){
start = false;
std::thread t1(setAnimation, message);
t1.detach();
return 1;
}
Above code is just an example to clarify my question.
Upvotes: 0
Views: 3172
Reputation: 1103
When creating your thread, you can pass a variable by reference using std::ref
However, you would still need to have your variable outside the function, else it will get out of scope.
std::thread t1(setAnimation, message, std::ref(myVariable));
Upvotes: 1