3
votes

If I have a global array that multiple threads are writing to and reading from, and I want to ensure that this array remains synchronized between threads, is using std::mutex enough for this purpose, as shown in pseudo code below? I came across with this resource, which makes me think that the answer is positive:

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.

I'm still interested in other people's opinion.

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());
}
1
Yes. std::mutex is used for synchronizationNathanOliver
Well, are your going to second-guess everything you've read on cppreference here? As a general rule (though with some offs, but you will be hard-pressed to find those) cppreference is very reliable and sound source of evidence. Usually it is ultimate arbiter on StackOverflow, not the other way around ;)SergeyA

1 Answers

5
votes

This is precisely what mutexes are for. Just try not to hold them any longer than necessary to minimize the costs of contention.