Reputation:
The output of the code below is 4000; why it's 4000 if the thread which have the mutex doesn't release it. I though it will be a deadlock, in the main i wait for all the functions to finish.
int M = 1000;
HANDLE mutex;
DWORD WINAPI thread_function(LPVOID param) // The thread function
{
long aux;
WaitForSingleObject(mutex, INFINITE);
for (int i = 0; i < M; i++)
{
aux = count; //count is global
aux++;
Sleep(0.5);
count = aux;
}
/*ReleaseMutex(mutex);*/
return (DWORD)0;
}
int main()
{
int N = 4;
InitializeCriticalSection(&gSection);
HANDLE* iThread = (HANDLE*)malloc(N * sizeof(HANDLE));
mutex = CreateMutex(NULL, FALSE, NULL);
for (int i = 0; i < N; i++) // N = 4, i create 4 threads
{
iThread[i] = CreateThread(NULL, 0, thread_function, mutex, 0, NULL);
}
WaitForMultipleObjects(4, iThread, TRUE, INFINITE); // I wait for all threads to finish.
printf("%d", count);
}
expected result is deadlock, actual result is 4000(count = 4000).
Upvotes: 3
Views: 209
Reputation: 1270
The other threads are blocked until the thread holding the mutex ends. With the (normal) end of the thread the mutex is released automatically since nobody is left holding it. But using that feature is bad coding practice. You should always release a mutex explicit.
Upvotes: 5