I’m trying to implement mutual exchange on a multi-threaded program. I’m not sure if I’m doing it right, and it’s difficult to test.
In main.cpp, I have something like this:
//mutex handle
HANDLE hIOMutex = CreateMutex (NULL,FALSE,NULL);
//main
while (1) {
Sleep(STEP);
WaitForSingleObject(hIOMutex,INFINITE);
//DO STUFF
ReleaseMutex(hIOMutex);
}
return 0;
And in a function used by the other thread:
void Case::account_login(Connection* Con) {
//mutex handle
HANDLE hIOMutex = CreateMutex (NULL,FALSE,NULL);
WaitForSingleObject(hIOMutex,INFINITE);
//DO STUFF
ReleaseMutex(hIOMutex);
return;
}
Is this correct? Are the sections of code even using the same HANDLE or am I declaring them locally and therefore screwing up the functionality?
If I’ve missed out any vital information, let me know.
Thanks.
No, they are not using the same handle or the same mutex, for that matter (there may be multiple handles to the same mutex). In the posted code, the two threads each have their own mutex, which means access to common data protected by these two mutexes will not be “mutually exclusive”.
Your options are more or less:
Connectionstruct/classEdit: I put “make the handle a global variable” last for a good reason: it’s the worst choice in the group. However, since OP insisted on an example…