mutual-exclusion
Is my spin lock implementation correct and optimal?
Looks fine to me. Btw, here is the textbook implementation that is more efficient even in the contended case. void lock(volatile int *exclusion) { while (__sync_lock_test_and_set(exclusion, 1)) while (*exclusion) ; }
Conditional Variable vs Semaphore
Locks are used for mutual exclusion. When you want to ensure that a piece of code is atomic, put a lock around it. You could theoretically use a binary semaphore to do this, but that’s a special case. Semaphores and condition variables build on top of the mutual exclusion provide by locks and are used … Read more
Make sure only a single instance of a program is running
The following code should do the job, it is cross-platform and runs on Python 2.4-3.2. I tested it on Windows, OS X and Linux. from tendo import singleton me = singleton.SingleInstance() # will sys.exit(-1) if other instance is running The latest code version is available singleton.py. Please file bugs here. You can install tend using … Read more
std::unique_lock or std::lock_guard?
The difference is that you can lock and unlock a std::unique_lock. std::lock_guard will be locked only once on construction and unlocked on destruction. So for use case B you definitely need a std::unique_lock for the condition variable. In case A it depends whether you need to relock the guard. std::unique_lock has other features that allow … Read more