Python 中信号量的清理

发布于 2024-12-03 05:31:07 字数 528 浏览 1 评论 0原文

我正在使用信号量将工作交给 Python 中的另一个线程。即主线程将一个项目放入队列中,然后调用信号量的 release 方法;工作线程将在信号量上调用acquire,然后从队列中弹出一个项目来进行处理。

还有一个特殊的 TERMINATE 项,主机可以将其放入队列中,指示工作程序结束。我的问题是,工作人员是否应该在终止之前发出 acquire 来匹配信号量上任何未完成的 release ?信号量属于worker对象,线程终止后不再使用;然而,该进程可能会长期存在,并在将来创建许多工作对象/线程/信号量。

  1. 放弃计数非零的信号量是否安全? (我怀疑是这样,但我想仔细检查一下。)

  2. 无论是否安全,您(主观)认为在结束之前完全清理信号量“更好”吗?

我最感兴趣的是 Python(更具体地说是 CPython)中的信号量行为。然而,任何有关其他语言(例如 C 的 pthreads)中信号量的一般智慧也将受到欢迎。

I'm using a semaphore to hand work off to another thread in Python. I.e. the master thread will put an item on a queue, then call the semaphore's release method; the worker thread will call acquire on the semaphore, then pop an item off the queue to work on.

There's also a special TERMINATE item that the master can put on the queue, which instructs the worker to end. My question is, should the worker aim to issue acquires to match any outstanding releases on the semaphore, before it terminates? The semaphore belongs to the worker object and is not used again after the thread terminates; the process however may be long-lived and create many worker objects/threads/semaphores in future.

  1. Is it safe to abandon the semaphore with a non-zero count? (I suspect it is but I want to double check.)

  2. Regardless of whether it's safe, do you (subjectively) think it's "nicer" to fully clean up the semaphore before ending?

I'm mostly interested in the semaphore behaviour in Python (and more specifically CPython). However any general wisdom on semaphores in other languages, such as C's pthreads, would be welcome too.

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

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

发布评论

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

评论(1

梦境 2024-12-10 05:31:07

#1:是的,放弃计数非零的信号量是安全的。毕竟这只是一个值。

#2:减少代码量更好。努力编写最少量的清晰代码以实现正确的实现。

#1: Yes, it's safe to abandon the semaphore with a non-zero count. It's just a value after all.

#2: It's nicer to reduce the amount of code. Strive to write the minimum amount of clear code for a correct implementation.

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