Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WaitForSingleObject With timeout=0

I have a mutex created in non signaled state

HANDLE hmutex= CreateMutex(NULL,FALSE,"");---1

Now I am calling

DWORD dw = WaitForSingleObject(hmutex,0); ---2

Since hmutex is not signaled, WaitForSingleObject will return immediately but will state of hmutex will change to signaled??

If another thread calls this second statement what will happen?

like image 228
anand Avatar asked Dec 19 '25 19:12

anand


2 Answers

No, it won't change to signaled.

The following invariants are true about that call:

  • It returns immediately regardless of the mutex state.
  • The mutex becomes owned (non-signaled) regardless of its previous state.
  • The return value tells you whether you gained ownership or failed due to contention.

In all cases, someone owns the mutex. However, if another thread was owner, it could release the mutex at any time, so by the time the function returns several processor cycles later, it might be released (signalled).

like image 75
Ben Voigt Avatar answered Dec 22 '25 13:12

Ben Voigt


Don't think of mutex objects as being signaled or non-signaled. Instead, think about them as being owned or unowned.

The second parameter in the call below says that the mutex is initially unowned.

HANDLE hmutex= CreateMutex(NULL,FALSE,"");

The very first time the call below is made, the calling thread will take ownership of the mutex. If another thread makes the same call while the mutex is owned by the first thread, the return value will be WAIT_TIMEOUT (258 decimal, 102 hex).

DWORD dw = WaitForSingleObject(hmutex,0);

Here are some guidelines to follow. Use mutexes if you need to restrict access to a resource shared by multiple processes. If you are restricting access to a resource within a single process, use CRITICAL_SECTION instead. If you are wanting an object that one thread can use to signal another thread, use events.

like image 38
Matt Davis Avatar answered Dec 22 '25 13:12

Matt Davis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!