Chapter 12: Multithreaded Programming

example 12.1, page no. 211

In [18]:
"""
note: the output will differ from that given in textbook as Threading in Python differs from that in J
"""


def threadA():
    for i in range(1, 6):
        print "From Thread A: i = ", i
    print "Exit from A"

def threadB():
    for i in range(1, 6):
        print "From Thread B: i = ", i
    print "Exit from B"

def threadC():
    for i in range(1, 6):
        print "From Thread C: i = ", i
    print "Exit from C"

thread1 = Thread(target=threadA, args=())
thread2 = Thread(target=threadB, args=())
thread3 = Thread(target=threadC, args=())

thread1.start()
thread2.start()
thread3.start()
From Thread C: i =  1
From Thread C: i =  2
From Thread C: i =  3
From Thread C: i =  4
From Thread C: i =  5
Exit from C
From Thread A: i =  1
From Thread A: i =  2
From Thread A: i =  3
From Thread A: i =  4
From Thread A: i =  5
Exit from A
From Thread B: i =  1
From Thread B: i =  2
From Thread B: i =  3
From Thread B: i =  4
From Thread B: i =  5
Exit from B

example 12.2, page no. 217

In [2]:
"""
there is no yield or stop function for threads in Python. Demonstrating just sleep() function
"""

from threading import Thread

import time

def threadA():
    for i in range(1, 6):
        print "From Thread A: i = ", i
    print "Exit from A"

def threadB():
    for i in range(1, 6):
        print "From Thread B: i = ", i
    print "Exit from B"

def threadC():
    for i in range(1, 6):
        print "From Thread C: i = ", i
        time.sleep(0.5)
    print "Exit from C"

thread1 = Thread(target=threadA, args=())
thread2 = Thread(target=threadB, args=())
thread3 = Thread(target=threadC, args=())

thread1.start()
time.sleep(0.5)
thread2.start()
time.sleep(0.5)
thread3.start()
time.sleep(0.5)
From Thread A: i =  1
From Thread A: i =  2
From Thread A: i =  3
From Thread A: i =  4
From Thread A: i =  5
Exit from A
From Thread B: i =  1
From Thread B: i =  2
From Thread B: i =  3
From Thread B: i =  4
From Thread B: i =  5
Exit from B
From Thread C: i =  1
In [ ]:
#There is no way you can set priority for a thread in Python. Hence, example 12.3 is avoided

example 12.4, page no. 225

In [69]:
"""
There is no runnable interface in Python. Will use normal threading instead
"""

import threading
class X(threading.Thread):
    def run(self):
        for i in range(1, 11):
            print "ThreadX: ", i
        print "End of ThreadX"

runnable = X()
threadx = Thread()
threadx.start()
print "End of main thread"
runnable.run()
End of main thread
ThreadX:  1
ThreadX:  2
ThreadX:  3
ThreadX:  4
ThreadX:  5
ThreadX:  6
ThreadX:  7
ThreadX:  8
ThreadX:  9
ThreadX:  10
End of ThreadX