Confused about Mutex?
-
I am confused how to get mutex locks to work correctly. As part of my testing I wrote the following code: HANDLE hMutex = CreateMutex(NULL, FALSE, "ABC"); int result = WaitForSingleObject(hMutex, INFINITE); int result2 = WaitForSingleObject(hMutex, INFINITE); The first line creates a mutex, then the next line "locks" the mutex, then the next line waits for and tries to relock the mutex. It seems to me that the second Wait should never return (since the Mutex is already locked.) However, both Waits return immediately with the return code 0 (== WAIT_OBJECT_0). What am I missing?
-
I am confused how to get mutex locks to work correctly. As part of my testing I wrote the following code: HANDLE hMutex = CreateMutex(NULL, FALSE, "ABC"); int result = WaitForSingleObject(hMutex, INFINITE); int result2 = WaitForSingleObject(hMutex, INFINITE); The first line creates a mutex, then the next line "locks" the mutex, then the next line waits for and tries to relock the mutex. It seems to me that the second Wait should never return (since the Mutex is already locked.) However, both Waits return immediately with the return code 0 (== WAIT_OBJECT_0). What am I missing?
Your first line creates a mutex and your current thread owns it. Your current thread will continue owning it until you call ReleaseMutex(). In your second thread, WaitForSingleObject() will wait until the first thread calls RealeaseMutex(), after the first thread has released it, the second thread will own it. If the first thread wants to own it again, it must wait until the second thread releases it. understand? It doesn't work in your example because it's all in the same thread.
-
Your first line creates a mutex and your current thread owns it. Your current thread will continue owning it until you call ReleaseMutex(). In your second thread, WaitForSingleObject() will wait until the first thread calls RealeaseMutex(), after the first thread has released it, the second thread will own it. If the first thread wants to own it again, it must wait until the second thread releases it. understand? It doesn't work in your example because it's all in the same thread.
-
Yes, I get it, I tried in a separate thread and it works as expected. Thanks for your help.
welcome