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:
The thread that owns a mutex can specify the same mutex in repeated wait function calls without blocking its execution.
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.
It looks like you want the main thread to take the mutex on behalf of the secondary thread. Mutexes are tracked by thread, so you cannot take a mutex on behalf of somebody else. You might want to switch to a semaphore, which does not have owner tracking.
You used the mutex improperly: when you wait for a mutex you block until somebody else will release it.
The thread procedure must do its own lock/unlock (WaitForSingleObject and ReleaseMutex, in windows) as well as the main thread. The purpose is avoid that one thread interleave the output with another.
If you want to "join" a thread (do something after its termination) you can wait for it as well.
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);
_beginthreadex(NULL,NULL,&t,NULL,0,NULL);
Sleep(0);
WaitForSingleObject(mutex,INFINITE);
printf("HD\n");
ReleaseMutex(mutex);
}
Also: don't use infinite loops to stuck a thread (while(1) ...
), use Sleep
instead.
Note also that -in general- you cannot predict what thread will printf first. That's what concurrency is for: the threads compete each other running in parallel. The mutex avoid them to output together, but what sequence will result depends also on what else the system is doing while running your program.
精彩评论