P
P
pixik2015-11-27 15:40:57
linux
pixik, 2015-11-27 15:40:57

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();
}

then another thread, when it encounters a section where a lock occurs on line 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?)
Not only the mutex case is interesting, but also the locking primitives and threading in general. Is there any interesting literature or tutorials on this?
upd: interested in case of unix like systems.
Thanks to all!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MiiNiPaa, 2015-11-27
@pixik

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.

V
Vladimir Martyanov, 2015-11-27
@vilgeforce

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 question

Ask a Question

731 491 924 answers to any question