4 ms·
How are latches implemented? Is it more efficient than just a condition variable?
by ridiculous_fish 6y ago
How are latches implemented? Is it more efficient than just a condition variable?
- amluto 6y agoAlmost certainly. Condition variables are very complicated internally. On Linux, a latch could be backed by a futex with very little code.
- ridiculous_fish 6y agoWhat is the source of the complexity inside condition variables? Reading the glibc sources, the main problem seems to be ensuring that signals are delivered properly?
- zvrba 6y agoYes, atomic unlock + wait is the complex bit. Prior to Vista, Windows did not have a CV primitive. Existing emulations used multiple kernel objects and their correctness was difficult to verify. Performance also suffered.
- gpderetta 6y agoI think Vista implemented keyed synchronization objects (i.e. a flavour of futexes) which have similar edge triggered semantics as CVs.
- atq2119 6y agoIt's possible to implement very simple condition variables. The tricky part is preventing correct but inefficient behaviours like stampeding herds.
- gpderetta 6y agoWhen implementing posix semantics there are a lot of nasty corner cases, especially with dealing with fairnes, graceful destruction, correct handling of wait generations and probably more that I'm missing. I would never attempt to implement a full condvar.
- halayli 6y agoTypical implementations use std::atomic or a variation of it (further stripped version of it).
- deleted 6y ago[deleted]
- searealist 6y agoProbably atomic increment / decrement + condition_variable. Just check if you hit 0 on decrement to notify waiters (or return if you are the waiter).
- ridiculous_fish 6y agoWell now that sounds like a semaphore!
- Skunkleton 6y agoCheck out futexes [1]. I did a quick scan of the llvm libcxx sources and latch and other threading primitives are based on this syscall. [1] https://en.wikipedia.org/wiki/Futex https://en.wikipedia.org/wiki/Futex
- ridiculous_fish 6y agoRight, and futexes also back condition variables in glibc.
- DSingularity 6y agoAnd mutexes too!
- tomcam 6y agoI prefer the modern nutex construct