使用简单的 CRITICAL_SECTION,似乎陷入僵局

发布于 2025-01-07 14:41:34 字数 982 浏览 0 评论 0原文

我有一个使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

じее 2025-01-14 14:41:34

for 循环中出现错误。应该是:

for(int i=0;i<N;++i)
{ // <---
      EnterCriticalSection(&cs);
      ++(*x);
      LeaveCriticalSection(&cs);
} // <---

没有大括号,因此 for 循环仅执行 EnterCriticalSection() 而没有执行其他任何操作。获取临界区的第一个线程从未释放它:死锁

Mistake in for loop. Should be:

for(int i=0;i<N;++i)
{ // <---
      EnterCriticalSection(&cs);
      ++(*x);
      LeaveCriticalSection(&cs);
} // <---

No braces so the for loop only executed EnterCriticalSection() and nothing else. The first thread that acquired the critical section never released it: deadlock.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文