Originally Posted by
rchiu5hk
I have the question about synchronization after looking at some articles in the web.
If I am using mutex for controlling the unique session resource, what will happen if there exists several thread which want to request the session resource which is in use? As I don't know how to put them in queue and how the first waiting get the session resource? It is mainly in coding sample as I want.
If two or more threads request the MUTEX object, only one of them gets it, the other thread(s) block until the MUTEX becomes available. When a thread releases a MUTEX object the thread scheduler wakes up the next waiting thread on that object and gives it control of the MUTEX. If a thread acquires the MUTEX and fails to release it, it can cause a deadlock on all other waiting threads.. There is no guarantee that the first thread to wait on the mutex will be the first to get it, but in general the kernel tries to be 'fair'. Meaning one thread wont usually get the mutex twice while another hasnt gotten it once.
Code:
#include <windows.h>
#include <stdio.h>
HANDLE Mutex;
DWORD WINAPI ThreadFunc(LPVOID pThreadNum){
WaitForSingleObject(Mutex , INFINITE);
char myString[256];
sprintf(myString , "Thread #%d Got the MUTEX.\n\0" , *(DWORD*)pThreadNum);
int x = 0;
while(myString[x]){
printf("%c" , myString[x]);
Sleep(rand() % 100 + 100 + (100 * *(DWORD*)pThreadNum));
x++;
}
ReleaseMutex(Mutex);
return 0;
}
DWORD WINAPI AsyncThreadFunc(LPVOID pThreadNum){
// WaitForSingleObject(Mutex , INFINITE);
char myString[256];
sprintf(myString , "Thread #%d Got the MUTEX.\n\0" , *(DWORD*)pThreadNum);
int x = 0;
while(myString[x]){
printf("%c" , myString[x]);
Sleep(rand() % 100 + 100 + (100 * *(DWORD*)pThreadNum));
x++;
}
//ReleaseMutex(Mutex);
return 0;
}
int main(){
DWORD ThreadId = 0;
Mutex = CreateMutex(NULL , FALSE , TEXT("MyMutex"));
DWORD ThreadNumber1 = 0;
HANDLE Thread1 = CreateThread(NULL , 0 , ThreadFunc , (LPVOID)&ThreadNumber1 , 0 , &ThreadId);
DWORD ThreadNumber2 = 1;
HANDLE Thread2 = CreateThread(NULL , 0 , ThreadFunc , (LPVOID)&ThreadNumber2 , 0 , &ThreadId);
WaitForSingleObject(Thread1 , INFINITE);
WaitForSingleObject(Thread2 , INFINITE);
ThreadNumber1 = 0;
Thread1 = CreateThread(NULL , 0 , AsyncThreadFunc , (LPVOID)&ThreadNumber1 , 0 , &ThreadId);
ThreadNumber2 = 1;
Thread2 = CreateThread(NULL , 0 , AsyncThreadFunc , (LPVOID)&ThreadNumber2 , 0 , &ThreadId);
WaitForSingleObject(Thread1 , INFINITE);
WaitForSingleObject(Thread2 , INFINITE);
return 0;
}