Wednesday, September 12, 2012

Threading in Python

My previous post were related to server and client. I need to enhance my server
so that it can handle multiple clients.

To handle such requirement i thought to redesign my server. Each client request
to server and server will start download in separate thread for requested url.
This will enhance my server design and now my server can handle multiple client
simultaneously.

So here is some threading concepts in python:

There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass.

A simple example:

 import threading
 import datetime
        
 class ThreadClass(threading.Thread):
          def run(self):
            now = datetime.datetime.now()
            print "%s says Hello World at time: %s" % 
            (self.getName(), now)
        
 for i in range(2):
          t = ThreadClass()
          t.start()
 
Another more simplistic example :

import time
from threading import Thread

def myfunc(i):
    print "sleeping 5 sec from thread %d" % i
    time.sleep(5)
    print "finished sleeping from thread %d" % i

for i in range(10):
    t = Thread(target=myfunc, args=(i,))
    t.start()

-- :) B-)
       
Reference :
http://docs.python.org/library/threading.html
http://www.ibm.com/developerworks/aix/library/au-threadingpython/
http://www.saltycrane.com/blog/2008/09/simplistic-python-thread-example/

Source code:
https://github.com/subh007/Python/blob/master/multithread1.py
https://github.com/subh007/Python/blob/master/multithread.py
 
 

No comments:

Post a Comment