1

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I read the doc, but I did not understand it. I thought (wrongly) that the default value had the behavior I wanted. You are right, with your solution, it works!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.