使用简单的 CRITICAL_SECTION,似乎陷入僵局
我有一个使用 CRITICAL_SECTION 的简单 C 程序。 由于某种原因它似乎一次又一次地进入CRITICAL_SECTION并且没有真正执行里面的代码,导致线程死锁。 我似乎找不到原因。
这是代码:
#include <windows.h>
#include <iostream>
#define N 100000000
CRITICAL_SECTION cs;
static DWORD WINAPI safe_increment(void *param)
{
volatile long* x = (volatile long*)param;
for(int i=0;i<N;++i)
EnterCriticalSection(&cs);
++(*x);
LeaveCriticalSection(&cs);
return 0;
}
void main()
{
InitializeCriticalSection(&cs);
volatile long x = 0;
HANDLE h[2];
DWORD thread_id;
int x = 0;
h[0] = CreateThread(NULL,0,safe_increment,(void*)&x,0,&thread_id);
h[1] = CreateThread(NULL,0,safe_increment,(void*)&x,0,&thread_id);
WaitForMultipleObjects(2,h,TRUE,INFINITE);
CloseHandle(h[0]);
CloseHandle(h[1]);
DeleteCriticalSection(&cs);
std::cout << "Result of safe increment: " << x << "\n";
}
谢谢!
罗伊.
i have a simple C program that uses CRITICAL_SECTION.
for some reason it seem to enter the CRITICAL_SECTION again and again and not really execute the code inside, causing the threads to deadlocked.
i cannot seem to find the reason for this.
here is the code:
#include <windows.h>
#include <iostream>
#define N 100000000
CRITICAL_SECTION cs;
static DWORD WINAPI safe_increment(void *param)
{
volatile long* x = (volatile long*)param;
for(int i=0;i<N;++i)
EnterCriticalSection(&cs);
++(*x);
LeaveCriticalSection(&cs);
return 0;
}
void main()
{
InitializeCriticalSection(&cs);
volatile long x = 0;
HANDLE h[2];
DWORD thread_id;
int x = 0;
h[0] = CreateThread(NULL,0,safe_increment,(void*)&x,0,&thread_id);
h[1] = CreateThread(NULL,0,safe_increment,(void*)&x,0,&thread_id);
WaitForMultipleObjects(2,h,TRUE,INFINITE);
CloseHandle(h[0]);
CloseHandle(h[1]);
DeleteCriticalSection(&cs);
std::cout << "Result of safe increment: " << x << "\n";
}
thank you!
Roy.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
for
循环中出现错误。应该是:没有大括号,因此
for
循环仅执行EnterCriticalSection()
而没有执行其他任何操作。获取临界区的第一个线程从未释放它:死锁。Mistake in
for
loop. Should be:No braces so the
for
loop only executedEnterCriticalSection()
and nothing else. The first thread that acquired the critical section never released it: deadlock.