Python 中信号量的清理
我正在使用信号量将工作交给 Python 中的另一个线程。即主线程将一个项目放入队列中,然后调用信号量的 release
方法;工作线程将在信号量上调用acquire
,然后从队列中弹出一个项目来进行处理。
还有一个特殊的 TERMINATE 项,主机可以将其放入队列中,指示工作程序结束。我的问题是,工作人员是否应该在终止之前发出 acquire
来匹配信号量上任何未完成的 release
?信号量属于worker对象,线程终止后不再使用;然而,该进程可能会长期存在,并在将来创建许多工作对象/线程/信号量。
放弃计数非零的信号量是否安全? (我怀疑是这样,但我想仔细检查一下。)
无论是否安全,您(主观)认为在结束之前完全清理信号量“更好”吗?
我最感兴趣的是 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 acquire
s to match any outstanding release
s 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.
Is it safe to abandon the semaphore with a non-zero count? (I suspect it is but I want to double check.)
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
#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.