Sunday, 20 December 2015

Python: Threads: with: Acquire lock, conditions, semaphores

By using with statement, you can acquire a lock, conditions, semaphores in simple way.

with some_lock:
    # do something...
   
is equivalent to:

some_lock.acquire()
try:
    # do something...
finally:
    some_lock.release()

‘with’ automatically release the lock after completion.


MyThread.py
import threading
import time

class MyThread(threading.Thread):
 def run(self):
  name=threading.current_thread().getName()
  
  global numberLock
  
  with numberLock:
   if(name=="even"):
    for i in range(2, 10, 2):
     time.sleep(0.5)
     print("Even Number :", i)
   else:
    for i in range(1, 10, 2):
     time.sleep(0.5)
     print("Odd Number :", i)
 
global numberLock
numberLock = threading.Lock()
 
thread1 = MyThread(name="even")
thread2 = MyThread(name="odd")

thread1.start()
thread2.start()

$ python3 MyThread.py 
Even Number : 2
Even Number : 4
Even Number : 6
Even Number : 8
Odd Number : 1
Odd Number : 3
Odd Number : 5
Odd Number : 7
Odd Number : 9


Previous                                                 Next                                                 Home

No comments:

Post a Comment