multithreading - 更新线程变量 (c++)

标签 multithreading c++11

实际问题是,我尝试将新参数发送到正在运行的线程。 想法是更改线程中的变量,但没有用。 该代码应显示问题的简单示例。 更新后打印出来的变量test应该是1,但一直是0。 有人理解这个问题并可以提供帮助吗? 非常感谢!

#include <iostream>
#include <thread>

class MyThread {
public:
int test = 0;
void operator()() const {
    while (1)
    std::cout << test << std::endl;
}
/* other public or private class members */
};

int main() {
    MyThread mythread;
    std::thread t(mythread);
    mythread.test = 1;
    t.join();
    return 0;
}

最佳答案

从多个线程访问变量必须使用一种称为“原子”的特殊类型的变量。在这种情况下,因为它是一个 int,所以应该写成 std::atomic<int> test; .

您可以阅读更多有关原子和 C++ 内存模型的技术细节 here .

关于multithreading - 更新线程变量 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41650960/

相关文章:

java - 从多个线程修改 ArrayAdapter 时如何防止 ConcurrentModificationException?

java - 与自定义读写锁实现混淆

multithreading - 在 ABCL(武装熊)LISP 中,我如何创建后台子进程/后台线程?

java - 不同硬件上的线程

c++ - 在 protected 匿名 union 中的匿名结构中定义的成员仍然公开可见

algorithm - 使用 STL 运行长度使用 std::adjacent_find 对字符串进行编码

c++ - 函数返回如何返回特定计数

Java 线程 - 奇怪的 Thread.interrupted() 和 future.cancel(true) 行为

c++ - 带有非类型模板参数的 std::enable_if

c++ - 构造函数转换