【问题标题】:Access variable in main thread from second thread从第二个线程访问主线程中的变量
【发布时间】:2017-03-29 13:54:49
【问题描述】:

我有一个函数 (messageArrived),它在一个新线程中调用一个函数 (setAnimation)。如何访问在 messageArrived 函数中定义的布尔值并在第二个线程中访问它?

如果有新消息我想终止第二个线程(setAnimation)。我认为布尔值是“终止”线程的唯一方法。

#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;
}

上面的代码只是澄清我的问题的一个例子。

【问题讨论】:

  • 与任何其他函数一样,您需要通过指向函数的指针/引用来传递它。
  • 局部变量在定义它们的范围内是局部的。线程不会改变这一点。
  • 这没什么意义,因为当messageArrived 返回时,start 不复存在,因此您无法访问。
  • @Janoshh 你已经有了你想要的。只需将该布尔值设为std::atomic&lt;bool&gt; 即可避免竞争条件。我不得不说这是设计上的一场灾难,但它应该可以工作。
  • @TheQuantumPhysicist:好的!你有更好的设计建议吗?

标签: c++ multithreading c++11 boolean thread-safety


【解决方案1】:

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

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

【讨论】:

  • 如果布尔值在 main 中设置为 false,第二个线程中的 whileloop 会注意到这种变化吗?
  • 这将导致线程引用超出范围的变量,并且OP将具有未定义的行为
  • @Janoshh 它是对布尔值的引用,所以是的,更改将在线程内“可见”。
  • @Someprogrammerdude:我是 C++ 编程新手。如果我理解你的答案,通过使用 std::ref 传递布尔值,线程将终止,但这不是一种保存方法?
  • 这个解决方案是错误的。 start 是全球性的!你为什么要在这里通过引用传递东西?
猜你喜欢
  • 1970-01-01
  • 2013-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多