Threads in Python PDF Print E-mail
Written by JLangbridge   
Tuesday, 22 May 2012 14:36

What is threading? Threading is the art of making concurrent code, little bits of a program that can run at (more or less) the same time, for added flexibility, and in some cases, speed. A threaded program can have a part dedicated to a certain task; for instance a program doing a complex long calculation may split into two threads, one to keep a user interface responsive, and one (or more) to progress through the lengthy calculation.

Threading in Python is easy. First thing you need to do is to import Thread using the following code:

from threading import Thread

There, easy. Now, in order to create a thread, we need to subclass the Thread class:

class MyThread(Thread):

We have now created a MyThread class, a child class of the Thread class. In order for a thread class to be of any use, we have to define a run() method. Threads will be called by the start() method, which in turn calls the run() method, so there is no need to init any messy thread configurations, everything is done for you. So let's create a simple thread class:

class MyThread(Thread):
 def __init__(self):
 """  Constructor  """
 Thread.__init__(self)
 
 def run(self):
 print "Hello, world!"

Nice and simple, straight to the point. Here's how we call it:

1
2
3
4
5
if __name__ == "__main__":
 #Create a MyObject class
 myThreadObj = MyThread()
 myThreadObj.setName("My Thread")
 myThreadObj.start()

Let's go through this. On line 3, we create a simple object. On line 4, we set the name of the thread. On line 5, we start the thread. start() will call our run() method, and will print out "Hello, world!". However, this doesn't actually do anything, since the thread will stop as soon as it starts, and even worse, the parent program has nothing else to do and will probably exit before the thread is even run, thus killing it. We need to make a few modifications:

1
2
3
4
5
6
7
8
9
10
11
12
13
class MyThread(Thread):
 
 def __init__(self):
 """
 Constructor
 """
 Thread.__init__(self)
 
 
 def run(self):
 for i in range(1, 10):
 print "Hello from " + self.getName()
 sleep(5)

The code is almost the same as before, except this time we will keep it busy for a few seconds. We will print out the name of the thread every 5 seconds.

This time, we will wait until the threads have finished before exiting. Our main application will look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
if __name__ == "__main__":
 #Create some MyObject objects:
 myThreadObj1 = MyThread()
 myThreadObj1.setName("Thread 1")
 
 myThreadObj2 = MyThread()
 myThreadObj2.setName("Thread 2")
 
 #Now start the threads
 myThreadOb1.start()
 myThreadOb2.start()
 #wait for the threads to finish...
 myThreadOb1.join()
 myThreadOb2.join()
 
 print "Goodbye"

And there you have it, a small application that runs 2 threads! Line 3 and 4 are like before; we create our thread object and give it a name. On line 10, we start the thread, but on line 13, we run join(), which will wait until the thread has finished. Once the 2 threads have finished, the main application prints "Goodbye", and the program exits.

 

 

 

 

 

 

 

 

 

Last Updated on Wednesday, 23 May 2012 07:56
 

Add comment


Security code
Refresh