In this post we will extend a previous
example about
multithreading. Here's how to synchronize two threads using a simple lock:
import threading
import thread
import time
class MyThread(threading.Thread):
def __init__(self, myName, lock):
threading.Thread.__init__(self)
self.myName = myName
self.lock = lock
def run(self):
while True:
self.lock.acquire()
print self.myName,'is in the critical section the lock'
time.sleep(1) # wait 1 second
print self.myName,'releasing the lock'
self.lock.release()
if __name__=="__main__":
lock=thread.allocate_lock()
thread1 = MyThread("1",lock)
thread1.start()
thread2 = MyThread("2",lock)
thread2.start()
while True: pass
A thread can't print in the console until he acquires the lock. The output will be similar to this:
1 is in the critical section the lock
1 releasing the lock
2 is in the critical section the lock
2 releasing the lock
1 is in the critical section the lock
1 releasing the lock
2 is in the critical section the lock
2 releasing the lock
2 is in the critical section the lock
2 releasing the lock
1 is in the critical section the lock
1 releasing the lock
2 is in the critical section the lock
2 releasing the lock
...
WARNING: This is a simple example with two threads and only one critical section, more complicated situation need other synchronization mechanisms.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.