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?
Understanding the Python Semaphores The Semaphore class consists of a constructor, and two functions, acquire() and release(), respectively. The acquire() function is used to decrease the count of the semaphore in case the count is greater than zero. Else it blocks till the count is greater than zero.
A thread waits for permission to proceed and then signals that the thread has proceeded by performing a P operation on the semaphore. The thread must wait until the semaphore's value is positive, then change the semaphore's value by subtracting 1 from the value.
A semaphore manages an internal counter which is decremented by each acquire() call and incremented by each release() call. The counter can never go below zero; when acquire() finds that it is zero, it blocks, waiting until some other thread calls release() . Semaphores also support the context management protocol.
Threading in python is used to run multiple threads (tasks, function calls) at the same time. Note that this does not mean that they are executed on different CPUs. Python threads will NOT make your program faster if it already uses 100 % CPU time. In that case, you probably want to look into parallel programming.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With