Python threads and semaphore

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

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() 

In the same way, thread1 sees the semaphore changes that thread2 does, and vice versa?

+6
source share
1 answer

For semaphore purposes, they allow you to safely synchronize parallel processes.

Keep in mind that threads in Python will not really get you concurrency unless you release the GIL (by doing IO, calling libraries, etc.). If this is what you are going for, you can consider the multiprocessing library.

+7
source

All Articles