14 April 2010

Hello Python Threads

I am looking for something new.

Java and I are going through a relationship crisis, in fact we are considering divorce. She has kept me awake for nights, talking a lot, saying not much. Broken promises, nerves on edge, where has the initial joy gone? Outside people I respect have warned me.

So last week I caught up again with a long gone lover. Her name is Python. It turned out the chemistry is still strong between us. She's now got a VIP membership at AppEngine, which made her even more attractive. She is a well-loved, public person and yet some things seam mysterious about her. Here a first little detail I figured out with some help.

Understanding by example - Python's threads:
Dispatch 4 threads, the first one running the longest with non-busy waiting for completion.

Source code:
import time 
from threading import Thread 
class MyThread(Thread): 
    def __init__ (self, id, seconds): 
        Thread.__init__(self) 
        self.id = id 
        self.seconds = seconds 
    def run(self): 
        print "Start running thread", self.id, "with seconds", self.seconds       
        for c in ("A","B","C"): 
            time.sleep(self.seconds) 
            print "thread", self.id, "at", c 
        print "Exit running thread", self.id, "with seconds", self.seconds      
 
if __name__ == "__main__": 
    myThreads = [] 
    for id in range(4): 
        #thread 0 runs slowest, thread 3 runs fastest 
        seconds = 4-id 
        t = MyThread(id, seconds) 
        myThreads.append(t) 
        t.start() 
 
    for myThread in myThreads: 
        myThread.join() 
        print "Done. ", myThread.id 

Output:
Start running thread 0 with sleep 4
Start running thread 1 with sleep 3
Start running thread 2 with sleep 2
Start running thread 3 with sleep 1
thread 3 at A
thread 2 at A
thread 3 at B
thread 1 at A
thread 3 at C
Exit running thread 3 with sleep 1
thread 0 at A
thread 2 at B
thread 1 at B
thread 2 at C
Exit running thread 2 with sleep 2
thread 0 at B
thread 1 at C
Exit running thread 1 with sleep 3
thread 0 at C
Exit running thread 0 with sleep 4
Done. 0
Done. 1
Done. 2
Done. 3

No comments:

Post a Comment