Reputation: 34523
Using the WaitForSingleObject Function.
If the function is called and times out, does it still need to release the mutex?
i.e. should ReleaseMutex be in position 1.
or 2.
if the five seconds elapse?
WaitForSingleObject(5 second time out)
{
//access shared resource
//1. - ReleaseMutex() here?
}
//2. - ReleaseMutex() here?
Upvotes: 4
Views: 436
Reputation: 5635
You only need to release the mutex if you got ownership. Note that there are 4 possible return values, in 2 cases you get ownership, and in 2 you do not.
WAIT_ABANDONED - you got ownership and need to release the mutex, but the previous owner terminated without explicitly releasing the mutext so shared state may be inconsistent.
WAIT_OBJECT_0 - you got the ownership. You need to release the mutext.
WAIT_TIMEOUT - the mutext was not released for the duration of timeout
WAIT_FAILED - usually due to a bug in your code (i.e. invalid handle).
Upvotes: 2
Reputation: 19034
Your case #1 is correct. If you time out on that call, it means the resource was not acquired and you should not attempt to release it.
Upvotes: 2
Reputation: 68561
No. If the call to WaitForSingleObject
times out then you have not acquired the mutex, so should not release it.
i.e. you only need ReleaseMutex
at position 1.
Upvotes: 6