|
-
September 11th, 2012, 09:55 AM
#9
Re: Do I need to worry about a failure in these synchronization APIs?
Critical sections have their uses. So do mutexes.
It's your job as a programmer to pick the most appriopriate solution, not the most programmatically convenient one.
Critical sections are intended for what it's name implies. a "critical section of code" where you don't want 2 threads to enter the section of code that guarded by the CS object (note that you can have more than one bit of code guarded by the same CS object). So you would typically lock and unlock the CS in the same block of code as part of the normal flow of code through that code. A typical CS will be locked only for a very short amount of time.
This is what a CS is intended for AND what it is optimised for. In this (and only this) approach it will provide the best overall performance.
You _can_ use a CS as a more generic lock in a lock it somewhere, and unlock it in a totally different bit of code, but that's really not what you should be using a CS for, that's what mutexes are intended for.
Why does this matter ? Because a CS does NOT yield to another thread when the CS appears locked. Instead the CS assumes that it'll become available "soon" and starts spinning in a loop. If the CS does indeed come available, you win and code proceeds without a costly context switch. if it doesn't, you loose... because you waited in vain for the CS to become available.
Mutexes otoh are intended for a lock and release type approach on a shared resource and where it is expected that the lock will remain for more than the typical time in a timeslice.
You can use a mutex on a place where a CS would have worked. But you loose out in that case. a mutex is many many times slower to lock and release than a critical section. In addition, when the mutex is locked, the OS will typically yield te remaining timeslice immediately. if the lock is released "soon" after your attemt, you loose because you just lost the remaining time of your timeslice.
Learn to use CS and mutex appripriately, not because either one seems more programmatically convenient. They both have a specific purpose and different behaviour.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|