Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python threading and semaphore

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?

like image 223
exilonX Avatar asked Mar 18 '13 19:03

exilonX


People also ask

Does Python have semaphore?

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.

How are semaphores used with threads?

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.

How does semaphore work in Python?

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.

What is Python threading?

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.


1 Answers

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.

like image 109
Sean McSomething Avatar answered Oct 05 '22 23:10

Sean McSomething