Answer the question
In order to leave comments, you need to log in
How does std::mutex work at a low level?
Good time!
Please tell me where to read how mutex and similar synchronization primitives work at a low level? In fact, everything is clear if the thread executes:
mutex l;
f(){
...
l.lock();
...
l.unlock();
}
l.lock()
, is blocked until the first thread unlocks the mutex. In many programs I need to use multithreading (std::thread), and various locks. Work (in terms of multi-threaded interaction) is not bad. But I think they could be more effective if I understood how it works at a lower level. (Or am I wrong?) Answer the question
In order to leave comments, you need to log in
At the lowest level, synchronization is done using atomic instructions on the processor. Let's say it's fashionable to use an atomic exchange operation to write to cell 1. If the previous value was 0, then we now own some resource, if there is 1, then someone else has already taken it and we need to try again later.
At a higher level, the OS usually comes into play. Since the processes are isolated from each other and cannot communicate directly, the mediation of the operating system is necessary. How this is done depends on the system. Pick a specific one and google it:
StackOverdlow
question linux.die.net/man/2/futex
pthread sources (Which is used to implement std::tread, std::mutex, etc)
EDIT: And don't use lock/unlock directly. Wrap them in a lock_guard.
For Windows there is a "native" mutex object, suitable for synchronization between threads. API for working with it: CreateMutex, ReleaseMutex, CloseHandle. There is also a "critical section", it is not suitable for synchronization between processes. API: InitializeCriticalSection, EnterCriticalSection, LeaveCriticalSection, DeleteCriticalSection. Examples, detailed documentation - in MSDN.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question