简体   繁体   中英

Cleanup of semaphore in Python

I'm using a semaphore to hand work off to another thread in Python. Ie 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.

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM