如果一个线程锁定了一个互斥量并且没有解锁它,那么其他线程不应该被阻塞吗?
If a thread locks a mutex and doesn't unlock it, shouldn't be the rest of threads blocked?
下面代码的输出是4000;
如果具有互斥量的线程不释放它,为什么它是 4000。我虽然这将是一个僵局,但主要是我等待所有功能完成。
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);
}
预期结果是死锁,实际结果是 4000(count = 4000)。
其他线程被阻塞,直到持有互斥锁的线程结束。在线程的(正常)端,互斥量会自动释放,因为没有人持有它。但是使用该功能是糟糕的编码习惯。您应该始终显式释放互斥量。
下面代码的输出是4000; 如果具有互斥量的线程不释放它,为什么它是 4000。我虽然这将是一个僵局,但主要是我等待所有功能完成。
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);
}
预期结果是死锁,实际结果是 4000(count = 4000)。
其他线程被阻塞,直到持有互斥锁的线程结束。在线程的(正常)端,互斥量会自动释放,因为没有人持有它。但是使用该功能是糟糕的编码习惯。您应该始终显式释放互斥量。