Sé que threading.Lock() es igual a threading.Semaphore(1) .
¿También threading.Lock() es igual a threading.BoundedSemaphore(1) ?
Y recién vi threading.BoundedSemaphore() , ¿cuál es la diferencia entre ellos? Por ejemplo, en el siguiente fragmento de código (aplicando limitación en subprocesos):
import threading sem = threading.Semaphore(5) sem = threading.BoundedSemaphore(5)Un Semaphore se puede liberar más veces de las que se adquiere, y eso elevará su contador por encima del valor inicial. Un BoundedSemaphore no se puede elevar por encima del valor inicial.
from threading import Semaphore, BoundedSemaphore # Usually, you create a Semaphore that will allow a certain number of threads # into a section of code. This one starts at 5. s1 = Semaphore(5) # When you want to enter the section of code, you acquire it first. # That lowers it to 4. (Four more threads could enter this section.) s1.acquire() # Then you do whatever sensitive thing needed to be restricted to five threads. # When you're finished, you release the semaphore, and it goes back to 5. s1.release() # That's all fine, but you can also release it without acquiring it first. s1.release() # The counter is now 6! That might make sense in some situations, but not in most. print(s1._value) # => 6 # If that doesn't make sense in your situation, use a BoundedSemaphore. s2 = BoundedSemaphore(5) # Start at 5. s2.acquire() # Lower to 4. s2.release() # Go back to 5. try: s2.release() # Try to raise to 6, above starting value. except ValueError: print('As expected, it complained.')El módulo de subprocesamiento proporciona la clase Semaphore simple.
Un Semaphore proporciona un contador no limitado que le permite llamar a release() cualquier número de veces para incrementar.
Sin embargo, para evitar errores de programación, generalmente es una opción correcta usar BoundedSemaphore , que genera un error si una llamada release() intenta aumentar el contador más allá de su tamaño máximo.
EDITAR
Un semáforo tiene un contador interno en lugar de un indicador de bloqueo (en el caso de bloqueos), y solo se bloquea si más de un número determinado de subprocesos han intentado retener el semáforo. Dependiendo de cómo se inicialice el semáforo, esto permite que múltiples subprocesos accedan a la misma sección de código simultáneamente.