c++ - 从多个线程更改共享变量 C++

标签 c++ multithreading

我想知道是否有任何方法可以在 C++ 中实现从多个线程更改共享/全局变量

想象一下这段代码:

#include <vector>
#include <thread>

void pushanother(int x);

std::vector<int> myarr;

void main() {
    myarr.push_back(0);

    std::thread t1(pushanother, 2);

    t1.join();
}

void pushanother(int x) {
    myarr.push_back(x);
}

最佳答案

在这种特殊情况下,代码(除非线程上缺少连接)令人惊讶地正常。

这是因为std::thread的构造函数导致内存栅栏操作,第一个线程不会修改或读取此栅栏后的 vector 状态。

实际上,您已将 vector 的控制转移到第二个线程。

但是,修改代码以表示更正常的情况需要显式锁:

#include <vector>
#include <thread>
#include <mutex>

void pushanother(int x);

// mutex to handle contention of shared resource
std::mutex m;

// the shared resource
std::vector<int> myarr;

auto push_it(int i) -> void
{
    // take a lock...
    auto lock = std::unique_lock<std::mutex>(m);

    // modify/read the resource
    myarr.push_back(i);

    // ~lock implicitly releases the lock
}

int main() {

    std::thread t1(pushanother, 2);

    push_it(0);

    t1.join();
}

void pushanother(int x) {
    push_it(x);
}

关于c++ - 从多个线程更改共享变量 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46141455/

相关文章:

c++ - 终值公式显示了惊人数量的输出

c++ - 从 C++ 代码创建静态库并与 iPhone SDK 链接

c++ - Qt Qml 连接到上下文属性的 QObject 属性的信号

java - 线程(textView 和进度条)

c++ - Windows Spooler Events API 不会为网络打印机生成事件

c++ - Visual Studio 的对象文件

java - 多线程 Java ScriptEngine

python - 线程中的 PyV8 - 如何让它工作?

python - 如何让python进程在后台持续运行

c++ - 面向任务的线程池