The
concept of avoiding multiple threads to access the same functionality at a time
is known as Synchronization. We can apply synchronization by calling acquire() and release() methods of thread lock.
Example –
import threading
import time
class MyThread(threading.Thread):
def __init__(self,id,name,count):
threading.Thread.__init__(self)
self.id=id
self.name=name
self.count=count
def run(self):
print 'Starting '+self.name
threadLock.acquire()
print_time(self.name,self.count,3)
threadLock.release()
def print_time(tname,delay,count):
while count:
time.sleep(delay)
print "%s %s "%(tname,time.ctime(time.time()))
count -=1
threadLock=threading.Lock()
threads = []
thread1=MyThread(1,"Thread1",1)
thread2=MyThread(2,"Thread2",2)
thread1.start()
thread2.start()
threads.append(thread1)
threads.append(thread2)
for i in threads:
i.join()
print "Exiting thread"
import time
class MyThread(threading.Thread):
def __init__(self,id,name,count):
threading.Thread.__init__(self)
self.id=id
self.name=name
self.count=count
def run(self):
print 'Starting '+self.name
threadLock.acquire()
print_time(self.name,self.count,3)
threadLock.release()
def print_time(tname,delay,count):
while count:
time.sleep(delay)
print "%s %s "%(tname,time.ctime(time.time()))
count -=1
threadLock=threading.Lock()
threads = []
thread1=MyThread(1,"Thread1",1)
thread2=MyThread(2,"Thread2",2)
thread1.start()
thread2.start()
threads.append(thread1)
threads.append(thread2)
for i in threads:
i.join()
print "Exiting thread"
Output –
Starting
Thread1
Starting
Thread2
Thread1
Tue Feb 07 20:47:03 2017
Thread1
Tue Feb 07 20:47:04 2017
Thread1
Tue Feb 07 20:47:05 2017
Thread2
Tue Feb 07 20:47:07 2017
Thread2
Tue Feb 07 20:47:09 2017
Thread2
Tue Feb 07 20:47:11 2017
Exiting
thread
Old Version Multithreading
import thread import time def print_time(tname,delay): count=0 while count<5: time.sleep(delay) count +=1 print '%s %s '%(tname,time.ctime(time.time()))
try: thread.start_new_thread(print_time,("Thread1",2,)) thread.start_new_thread(print_time,("Thread2",4,))
except: print 'Error : Unable to start'
while 1: pass
Output –
Thread1
Tue Feb 07 21:02:54 2017
Thread2
Tue Feb 07 21:02:56 2017
Thread1
Tue Feb 07 21:02:56 2017
Thread1
Tue Feb 07 21:02:58 2017
Thread2
Tue Feb 07 21:03:00 2017
Thread1
Tue Feb 07 21:03:01 2017
Thread1
Tue Feb 07 21:03:03 2017
Thread2
Tue Feb 07 21:03:04 2017
Thread2
Tue Feb 07 21:03:09 2017
Thread2
Tue Feb 07 21:03:13 2017
No comments:
Post a Comment