6

I have a python class let's call it AClass and another one MyThread which extends Thread. And in that AClass I make 2 objects of the class MyThread and I also have a semaphore which I give it as a parameter to the constructor of the MyThread class. My question is if I modify the semaphore in one MyThread object will the other MyThread object see the difference? Ex:

class AClasss:

     def function: 
          semafor = threading.Semaphore(value=maxconnections)
          thread1 = Mythread(semafor)
          thread2 = Mythread(semafor)
          thread1.start()
          thread1.join()
          thread2.start()
          thread2.join()

 class MyThread(Thread):
     def __init__(self,semaphore):
         self.semaphore = semaphore
     def run():
        semaphore.acquire()
        "Do something here" 
        semaphore.release()

So does thread1 see the changes to the semaphore that thread2 does and vice versa?

1 Answer 1

7

That's the purpose of semaphores, they allow you to safely synchronize concurrent processes.

Keep in mind that threads in Python won't really get you concurrency unless you're releasing the GIL (doing IO, calling libraries and so on). If that's what you're going for, you might want to consider the multiprocessing library.

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

1 Comment

great thanks, I though it was so but I wanted to be sure before staring coding.

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.