c:c_threads:protected_access_to_shared_data_or_shared_resources
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:
- Mutex: The classical way would be to protect access to a variable by a mutex.
- Writelock / Readlock: Usually cheaper than mutexes.
- Atomic Read & Write: Since C++ 11. Also called lockless. Atomic is here to ensure no races are to be expected while accessing a variable.
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.
c/c_threads/protected_access_to_shared_data_or_shared_resources.txt · Last modified: 2021/06/08 09:45 by peter