Win32 互斥体不等待

发布于 2024-08-07 22:52:57 字数 1098 浏览 4 评论 0原文

我正在创建一个实现进程间通信的应用程序。 为此,我设置了一个共享缓冲区,看起来效果很好。 现在,我需要一种数据生成应用程序的方法(用 C++ 编写) 告诉数据接收应用程序(用 freepascal/lazarus 编写) 什么时候应该读取数据。

我试图使用互斥体来达到此目的。我对 windows api 编程没有太多经验。

所以,我的问题是,在下面的 FreePascal 代码中,互斥体不会等待。我可以调用 TMutex.Wait() 函数,它不会返回错误或任何内容,但它根本不会等待。

构造函数 TMutex.Create(sName: AnsiString);
开始
  sName := 'Local\Mutex'+sName;
hMutex := CreateMutexA(
       nil, // 默认访问
        True, // 最初不拥有
      PChar(sName)); // 命名互斥体
  如果 hMutex = 0 则
  开始
   引发 Exception.Create('互斥体创建失败');
  结束;
结束;

析构函数 TMutex.Destroy;
开始
  CloseHandle(hMutex);
结束;

过程 TMutex.Wait;
开始
if (WaitForSingleObject(hMutex, INFINITE) <> 0) then ShowMessage('调试:等待返回某些内容');
结束;

过程 TMutex.Post;
开始
  ReleaseMutex(hMutex);
结尾;

I am creating an application that implements inter process communication.
For this purpose I have set up a shared buffer, which seems to work fine.
Now, I need a way for the data generating application (written in c++)
to tell the data receiving application (written in freepascal/lazarus)
when it should read the data.

I was trying to use a mutex for this purpose. I do not have much experience with windows api programming.

So, my problem is, in the FreePascal code below, the mutex won't wait. I can call the TMutex.Wait() function, it doesn't return an error or anything, but it simply won't wait.

constructor TMutex.Create(sName: AnsiString);
begin
  sName := 'Local\Mutex'+sName;
  hMutex := CreateMutexA(
        nil, // default access
        True, // initially not owned
        PChar(sName)); // named mutex
  if hMutex = 0 then
  begin
    raise Exception.Create('mutex creation failed');
  end;
end;

destructor TMutex.Destroy;
begin
  CloseHandle(hMutex);
end;

procedure TMutex.Wait;
begin
  if (WaitForSingleObject(hMutex, INFINITE) <> 0) then ShowMessage('debug: wait returned something');
end;

procedure TMutex.Post;
begin
  ReleaseMutex(hMutex);
end;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

傲世九天 2024-08-14 22:52:57

看起来你的问题在于:

    True, // initially not owned

你的东西是倒退的——true意味着它最初是被拥有的,所以等待它会立即返回。

It looks like your problem is at:

    True, // initially not owned

You have things backwards -- true means it initially IS owned, so waiting on it will return immediately.

故事灯 2024-08-14 22:52:57

您没有向我们展示调用 TMutex 的 Wait 方法的代码。但是,您必须知道互斥锁是可重入的:如果线程拥有互斥锁,则它将始终被授予对其的访问权限,因此等待永远不会阻塞。这是内置于互斥体中以避免死锁的。

尝试从另一个线程获取互斥体,等待应该阻塞。

you don't show us the code that calls the Wait, method of TMutex. however, you have to know that a mutex is reentrant: if a thread owns a mutex, it will always be granted access to it, thus a wait will never block. this is built into the mutex to avoid deadlocks.

try acquiring the mutex from another thread, the wait should block.

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