c++ - std::mutex 是否足以实现线程间的数据同步

标签 c++ multithreading c++11 locking mutex

如果我有一个多个线程正在写入和读取的全局数组,并且我想确保这个数组在线程之间保持同步,那么使用 std::mutex 是否足够用于此目的,如下面的伪代码所示?我遇到了 this resource ,这让我认为答案是肯定的:

Mutual exclusion locks (such as std::mutex or atomic spinlock) are an example of release-acquire synchronization: when the lock is released by thread A and acquired by thread B, everything that took place in the critical section (before the release) in the context of thread A has to be visible to thread B (after the acquire) which is executing the same critical section.

我仍然对其他人的意见感兴趣。

float * globalArray;
std::mutex globalMutex;

void method1() 
{
    std::lock_guard<std::mutex> lock(globalMutex);
    // Perform reads/writes to globalArray
}

void method2() 
{
    std::lock_guard<std::mutex> lock(globalMutex);
    // Perform reads/writes to globalArray
}

main() 
{
    std::thread t1(method1());
    std::thread t2(method2());
    std::thread t3(method1());
    std::thread t4(method2());
    ...
    std::thread tn(method1());
}

最佳答案

这正是互斥锁的用途。尽量不要将它们保留超过必要的时间,以最大限度地减少争用成本。

关于c++ - std::mutex 是否足以实现线程间的数据同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32771708/

相关文章:

c++ - 计算嵌套根式级数

c++ - sizeof 对齐的空结构

C++:我正在解决一个问题,突然我注意到编译的代码没有返回语句

C++11 - 绑定(bind)排序函数

c - 线程安全变量 comaprison C VS2010

Python:threading.Thread,值是按值传递还是按引用传递?

C++ 使用 lambda 函数作为模板函数特化

c++ - 使用 C++11 <random> 高效生成随机数

c++ - 如何评估 'if (A && B)' 语句?

python - 什么时候线程?