Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WaitForSingleObject: do not lock a mutex but check the current state?

Tags:

c

mutex

winapi

I'm currently using WaitForSingleObject((HANDLE)handle,INFINITE) function to mutex-lock some parts of my code.

Now I have a situation where I do not want to lock it but just peek, if it is in the locked-state. Using POSIX I can do that with pthread_mutex_trylock() - when it fails, I know there is already a lock on this mutex.

So: how can this be done with WaitforSingleObject()-call? How can I find out if the related mutex is already locked?

I guess it has something to do with the dwMilliseconds parameter, but I don't understand how I can find out if it is locked or just returned because of an other lock...

like image 380
Elmi Avatar asked Sep 21 '25 01:09

Elmi


1 Answers

WaitForSingleObject (family of functions) is used for effectively putting a thread to sleep while waiting on various types of Windows handles. Execution of the thread will wait until the function has returned. In the simplest case of using mutex, these functions also request a lock. The thread will keep the mutex locked until you call ReleaseMutex.

dwMilliseconds merely specifies the wait timeout. Normally you should use the constant INFINITE here. You can also pass the value 0 to dwMilliseconds to have the function check the status of the handle and immediately return and continue execution. If it returns WAIT_OBJECT_0 (or equivalent), you have the mutex lock. This is the equivalent to pthread_mutex_trylock.

In case you do specify a timeout, WaitForSingleObject will return a timeout status WAIT_TIMEOUT when it has not gotten the requested handle within the specified time period. In case of WaitForMultipleObjects, you also need to check the result to see which object you got.

Example from MSDN: https://learn.microsoft.com/en-us/windows/win32/sync/using-mutex-objects

like image 147
Lundin Avatar answered Sep 22 '25 20:09

Lundin