共享使用计数器的同步原语?

发布于 2024-09-09 05:30:19 字数 671 浏览 5 评论 0原文

是否存在 Windows(或 .NET)同步原语:

  • 可以在同一台 PC 上的多个进程之间共享;
  • 表示当前有多少线程依赖于共享资源的计数器;
  • 当进程异常终止时,操作系统会自动递减;并且
  • 可以由另一个进程等待(并在计数降至零时发出信号)?

我想在多个进程之间共享资源,然后在最后一个进程退出(无论正常还是异常)或声明资源已完成时关闭资源。启动时必须进行一些握手,但这是可行的;有趣的部分是等待进程退出。

据我所知,命名信号量(具有较高的初始计数)可以满足除最后一个要求之外的所有要求。但是信号量是递减计数而不是递增计数,而且我没有找到一种方法来等待信号量达到其最大计数。

如果不存在这样的原语,是否有一个 .NET 库可以创建类似的东西,或者有关如何构建它的信息?

(这是为了 我怎样才能等到Windows进程及其子进程全部退出?。但是,虽然这个问题有很多可能的方法,但在这里我特别想探讨同步对象是否能够胜任该任务。这是我想到的第一个方法,但我希望在这里了解它们是否真的适用于此。)

Is there a Windows (or .NET) synchronization primitive that:

  • can be shared across multiple processes on the same PC;
  • represents a counter of how many threads are currently depending on a shared resource;
  • is automatically decremented by the OS when a process abnormally terminates; and
  • can be waited on by another process (and signaled when the count drops to zero)?

I want to share a resource across multiple processes, and then close the resource when the last process exits (whether normally or abnormally) or declares that it's done with the resource. There would have to be some handshaking on startup, but that's doable; the interesting part is waiting for the processes to exit.

As far as I can tell, a named semaphore (with a high initial count) could satisfy all but the last requirement. But semaphores count down instead of up, and I don't see a way to wait for one to reach its maximum count.

If no primitive exists for this, is there a .NET library that creates something like it, or information on how to build one?

(This is for a possible implementation for How can I wait until a Windows process, and its subprocesses, have all exited?. But whereas that question has many possible approaches, here I specifically want to explore whether synchronization objects are up to the task. They're the first approach that occurred to me, but I'm hoping to learn something here about whether they really would work for this.)

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

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

发布评论

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

评论(1

夏尔 2024-09-16 05:30:19

不存在满足所有这些条件的原语。您必须构建自己的相当于 CountdownEvent 的跨进程。

There are no primitives that satisfy all these conditions. You'd have to build your own cross-process equivalent of CountdownEvent.

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