简体   繁体   English

从第二个线程访问主线程中的变量

[英]Access variable in main thread from second thread

I have a function (messageArrived) that call's a function (setAnimation) inside a new thread. 我有一个函数(messageArrived),该函数在新线程内调用一个函数(setAnimation)。 How can i access a boolean that is defined inside the messageArrived function and access it in the second thread? 如何访问在messageArrived函数内部定义的布尔值并在第二个线程中访问它?

If there is a new message i want to terminate the second thread (setAnimation). 如果有新消息,我想终止第二个线程(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. 上面的代码仅是一个示例,用于阐明我的问题。

创建线程时,可以使用std::ref通过引用传递变量,但是,您仍然需要将变量放在函数之外,否则它将超出范围。

std::thread t1(setAnimation, message, std::ref(myVariable));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM