gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:51:23 25 4
gpt4 key购买 nike

我想知道是否有任何方法可以在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com