I ran into this table in a concurrency training class. It gives you the quick and dirty on synchronization primitives available in Win32.
Characteristic
|
CriticalSection
|
SRWLocks
|
Mutex
Semaphores
Events
|
Kernel call even if free and upon creation
|
N
|
N
|
Y
|
Non-FIFO (no convoys)
|
Y
|
Y
|
N
|
Spin before wait option
|
Y
|
Y
|
N
|
Try to acquire option
|
Y
|
N/Y on Win7
|
N
|
Cross-process
|
N
|
N
|
Y
|
Recursive acquires
|
Y
|
N
|
Mutex only
|
Use in WaitForMultiple..
|
N
|
N
|
Y
|
- CriticalSections are the lightest weight and normally the best to use.
- you can use them recursively on the same thread
- SRWLocks are best if you need to differentiate reading and writing access. For example you can take a shared lock for read only access to a shared resource and exclusive lock for writing.
- It is generally better than just using a critical section if the ratio is 2 reads : 1 write
- Cannot be used recursively
- Mutex/Semaphores/Events are kernel objects
- Can be used across process.
- Obviously available in krenel mode.
- In user mode, the will be less performant than critical sections and SRWlocks and will cause more context switching.
- Are processed in convoys so they can avoid starvation
Instrumentation is the best way to know what kind of synchronization is best for your code. Look at my previous post on how to instrument with ETW and XPerf for industrial grade perf testing. Try different synchronization mechanisms and measure performance.
No comments:
Post a Comment