gpt4 book ai didi

c - 如果一个线程锁定了一个互斥量并且没有解锁它,那么其他线程不应该被阻塞吗?

转载 作者:太空狗 更新时间:2023-10-29 16:05:20 24 4
gpt4 key购买 nike

下面代码的输出是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)。

最佳答案

其他线程被阻塞,直到持有互斥量的线程结束。在线程的(正常)端,互斥量会自动释放,因为没有人持有它。但是使用该功能是糟糕的编码习惯。您应该始终显式释放互斥量。

关于c - 如果一个线程锁定了一个互斥量并且没有解锁它,那么其他线程不应该被阻塞吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55411769/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com