开发者

Cleanup of semaphore in Python

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.


#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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜