|
| 1 | +#Python multithreading example to demonstrate locking. |
| 2 | +#1. Define a subclass using Thread class. |
| 3 | +#2. Instantiate the subclass and trigger the thread. |
| 4 | +#3. Implement locks in thread's run method. |
| 5 | + |
| 6 | +import threading |
| 7 | +import datetime |
| 8 | + |
| 9 | +exitFlag = 0 |
| 10 | + |
| 11 | +class myThread (threading.Thread): |
| 12 | + def __init__(self, name, counter): |
| 13 | + threading.Thread.__init__(self) |
| 14 | + self.threadID = counter |
| 15 | + self.name = name |
| 16 | + self.counter = counter |
| 17 | + def run(self): |
| 18 | + print "Starting " + self.name |
| 19 | + # Acquire lock to synchronize thread |
| 20 | + threadLock.acquire() |
| 21 | + print_date(self.name, self.counter) |
| 22 | + # Release lock for the next thread |
| 23 | + threadLock.release() |
| 24 | + print "Exiting " + self.name |
| 25 | + |
| 26 | +def print_date(threadName, counter): |
| 27 | + datefields = [] |
| 28 | + today = datetime.date.today() |
| 29 | + datefields.append(today) |
| 30 | + print "%s[%d]: %s" % ( threadName, counter, datefields[0] ) |
| 31 | + |
| 32 | +threadLock = threading.Lock() |
| 33 | +threads = [] |
| 34 | + |
| 35 | +# Create new threads |
| 36 | +thread1 = myThread("Thread", 1) |
| 37 | +thread2 = myThread("Thread", 2) |
| 38 | + |
| 39 | +# Start new Threads |
| 40 | +thread1.start() |
| 41 | +thread2.start() |
| 42 | + |
| 43 | +# Add threads to thread list |
| 44 | +threads.append(thread1) |
| 45 | +threads.append(thread2) |
| 46 | + |
| 47 | +# Wait for all threads to complete |
| 48 | +for t in threads: |
| 49 | + t.join() |
| 50 | +print "Exiting the Program!!!" |
0 commit comments