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

Changing shared variables from multiple threads c++

本文关键字:共享变量 线程      更新时间:2023-10-16

我想知道是否有任何方法可以实现从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的构造函数会导致内存围栏操作,并且第一个线程不会修改或读取该栅栏后的向量状态。

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

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

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

我认为这是您问题的确切完整示例:

http://www.cplusplus.com/reference/mutex/mutex/