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++ - 与 chrono::duration<float> 一起使用时条件变量不会唤醒

c++11 - foo({1,2}) 如何为 "void foo(pair<int,int>)"工作

c++ - 奇怪的类型名用法 c++11

c++ - 调用CudaFree时,多线程CPU CUDA应用程序不异步

java - HashMap 在 2 种不同的方法上进行操作 - 多线程和并发

c++ - c++:为什么执行回调,但没有在回调定义之前执行功能?

java - 如何保护一种方法免受不同请求的影响

c++ - 自定义转换运算符的 Clang 歧义

c++ - 为 GCC 复制 clang 的 __builtin_assume