4

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?
T.T.T.
  • 33,367
  • 47
  • 130
  • 168

3 Answers3

6

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.

Anthony Williams
  • 66,628
  • 14
  • 133
  • 155
2

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.

Amardeep AC9MF
  • 18,464
  • 5
  • 40
  • 50
2

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).

BenMorel
  • 34,448
  • 50
  • 182
  • 322
John
  • 5,561
  • 1
  • 23
  • 39