如果我有一个多个线程正在写入和读取的全局数组,并且我想确保这个数组在线程之间保持同步,那么使用 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/