|Threads in Python|
|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:
There, easy. Now, in order to create a thread, we need to subclass the Thread class:
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:
Nice and simple, straight to the point. Here's how we call it:
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:
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:
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|