I have problem with mutexes
I have this code and I dont any idea why it doesn’t work correctly…
#include <windows.h>
#include <process.h>
#include <stdio.h>
HANDLE mutex;
unsigned _stdcall t(void*){
printf(":D:D:D\n");
return NULL;
}
int main(){
mutex=CreateMutex(NULL,FALSE,NULL);
WaitForSingleObject(mutex,INFINITE);
_beginthreadex(NULL,NULL,&t,NULL,0,NULL);
WaitForSingleObject(mutex,INFINITE);
printf("HD\n");
}
the result is :
HD
:D:D:D
I expect not to see HD in console…..
but this code work correctly
HANDLE mutex;
unsigned _stdcall t(void*){
WaitForSingleObject(mutex,INFINITE);
printf(":D:D:D\n");
ReleaseMutex(mutex);
return NULL;
}
int main(){
mutex=CreateMutex(NULL,FALSE,NULL);
WaitForSingleObject(mutex,INFINITE);
_beginthreadex(NULL,NULL,&t,NULL,0,NULL);
printf("HD\n");
while(1){
}
}
the result is:
HD
Thank you everyone….
As per MSDN:
Thus in your first sample, the second call to
WaitForSingleObject()doesn’t block the main thread as it is the thread that owns the mutex.