Should a mutex be released if it shuts down?

Using the WaitForSingleObject function.

If the function is called and disabled, do you still need to release the mutex?

i.e. Should ReleaseMutex be in position 1. or 2. if five seconds have elapsed?

 WaitForSingleObject(5 second time out) { //access shared resource //1. - ReleaseMutex() here? } //2. - ReleaseMutex() here? 
+4
source share
3 answers

No. If the WaitForSingleObject call expires, then you have not acquired the mutex, so you should not let it go.

i.e. you only need ReleaseMutex at position 1.

+6
source

Your business number 1 is true. If you time out on this call, it means that the resource has not been purchased, and you should not try to free it.

+2
source

You only need to free the mutex if you have obtained ownership. Please note that there are 4 possible return values, in 2 cases you get ownership, and in 2 you do not.

WAIT_ABANDONED - you obtained ownership and must release the mutex, but the previous owner stopped working without explicitly releasing the mutext, so the shared state may be inconsistent.

WAIT_OBJECT_0 - You have ownership. You need to free the mutext.

WAIT_TIMEOUT - Mutext was not released at timeout.

WAIT_FAILED - usually due to an error in your code (i.e. invalid handle).

+2
source

All Articles