Python Programming/Threading

From Wikibooks, the open-content textbooks collection
< Python Programming
Jump to: navigation, search
Previous: Email Index Next: Sockets

Threading in python is used to run multiple threads (tasks, function calls) at the same time. Note that this does not mean, that they are executed on different CPUs. Python threads will NOT make your program faster if it already uses 100 % CPU time, probably you then want to look into parallel programming. If you are interested in parallel progamming with python, please see here.

Python threads are used in cases where the execution of a task involves some waiting. One example would be interaction with a service hosted on another computer, such as a webserver. Threading allows python to execute other code while waiting; this is easily simulated with the sleep function.

[edit] Examples

[edit] A Minimal Example with Function Call

Make a thread that prints numbers from 1-10, waits for 1 sec between:

import thread
import time
 
def loop1_10():
    for i in range(1, 11):
        time.sleep(1)
        print(i)
 
thread.start_new_thread(loop1_10, ())

[edit] A Minimal Example with Object

#!/usr/bin/env python
import threading
import time
 
class MyThread(threading.Thread):
    def run(self):
        print("%s started!" % self.getName())
        time.sleep(1)
        print("%s finished!" % self.getName())
 
if __name__ == '__main__':
    for x in range(4):
        mythread = MyThread(name = "Thread-%d" % (x + 1))
        mythread.start()
        time.sleep(.9)

This should output:

Thread-1 started!
Thread-2 started!
Thread-1 finished!
Thread-3 started!
Thread-2 finished!
Thread-4 started!
Thread-3 finished!
Thread-4 finished! 

Note: this example appears to crash IDLE in Windows XP (seems to work in IDLE 1.2.4 in Windows XP though)

There seems to be a problem with this, if you replace Sleep(1) with (2) ,and change range (4) to range(10). Thread -2 finished is the first line before its even started. in WING IDE, Netbeans, eclipse is fine.

Previous: Email Index Next: Sockets
Personal tools
Namespaces
Variants
Actions
Navigation
Community
Print/export
Toolbox