C - C++ Threads - Protected access to shared data or shared resources

In a multi-threaded environment, more than one thread is often competing for a resource or shared data.

This often results in undefined behavior for the resource or data, unless the resource or data is protected using some mechanics that only allows ONE thread to act on it at a time.

There are different methods that can be used for this protection:

NOTE: Windows delivers an extraordinary bad performance with std::Mutex.

  • It seems as if in windows std::mutex is similar to std::recursive_mutex using the Critical_Section system call which has a significant larger overhead and is to be avoided.
  • SRW Locks are therefore preferred in Windows

On Unix and Mac OS X std::mutex is the way to go, as RW-Locks do not deliver better performance.


Atomic Read & Write

Mutex

Writelock / Readlock