Lets Synchronize Threads in Python
Lets Synchronize Threads in Python
Python
Because synchrony is harmony
of
def add_one():
"""
Just used for demonstration. It’s bad to use the ‘global’
statement in general.
"""
global g
lock.acquire()
g += 1
lock.release()
def add_two():
global g
lock.acquire()
g += 2
lock.release()
threads = []
for func in [add_one, add_two]:
threads.append(Thread(target=func))
threads[-1].start()
num = 0
lock = Threading.Lock()
lock.acquire()
num += 1
lock.acquire() # This will block.
num += 2
lock.release()
lock.acquire()
num += 3
lock.acquire() # This won’t block.
num += 4
lock.release()
lock.release() # You need to call release once for each call to acquire.
One good use case for RLocks is recursion, when a parent call of a function
would otherwise block its nested call. Thus, the main use for RLocks is nested
access to shared resources.
Semaphores
semaphore_tut.py in action
The threading module also provides the simple Semaphore class.
A Semaphore provides a non-bounded counter which allows you to
call release() any number of times for incrementing. However, to avoid
programming errors, it’s usually a correct choice to use BoundedSemaphore ,
which raises an error if a release() call tries to increase the counter beyond
it’s maximum size.
Semaphores are typically used for limiting a resource, like limiting a server to
handle only 10 clients at a time. In such a case, multiple thread connections
compete for a limited resource (in our example, it is the server).
Events
event = Event()
threads = []
nloops = random.randrange(3, 6)
print(“All done.”)
Execution of event_tut.py
Conditions
num = 4
# 4 threads will need to pass this barrier to get released.
b = Barrier(num)
names = [“Harsh”, “Lokesh”, “George”, “Iqbal”]
def player():
name = names.pop()
sleep(randrange(2, 5))
print(“%s reached the barrier at: %s” % (name, ctime()))
b.wait()
threads = []
print(“Race starts now…”)
for i in range(num):
threads.append(Thread(target=player))
threads[-1].start()
"""
Following loop enables waiting for the threads to complete before moving on
with the main script.
"""
for thread in threads:
thread.join()
print()
print(“Race over!”)