I am trying to use a Semaphore in Python to block the execution of a Thread, and release the Semaphore in another Thread depending on some conditions (in my case receiving some content over tcp).
But it is not working, my main Thread is not blocked like I though it would. My minimal example:
import time
from threading import Thread, Semaphore
class ServerManager():
sem = Semaphore()
def run(self):
time.sleep(15)
self.sem.release()
manager = ServerManager()
thread = Thread(target = manager.run)
thread.start()
manager.sem.acquire()
print("I am here immediately but should not")
The message is printed immediately in the console but should only be printed after 15 seconds in my example. I'm sure I did something horribly wrong, but what?
CodePudding user response:
You need to read the documentation about threading.Semaphore
. A semaphore blocks when a thread tries to acquire
and the counter is 0. When you create a Semaphore
, the default count is 1, so your acquire
is able to succeed immediately. I suspect you want
sem = Semaphore(0)
so the resource is immediately unavailable.
CodePudding user response:
The answer from Tim Roberts is right.I read the Python doc, but I did not understand it. I thought (wrongly) that the default value had the behavior I wanted. The full code is:
I should do:
import time
from threading import Thread, Semaphore
class ServerManager():
sem = Semaphore(0)
def run(self):
time.sleep(15)
self.sem.release()
manager = ServerManager()
thread = Thread(target = manager.run)
thread.start()
manager.sem.acquire()
print("I am here immediately but should not")
The message is printed after 15 seconds.