Python Programming/Threading

From Wikibooks, open books for an open world
Jump to navigation Jump to search

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. In that case, you probably want to look into parallel programming. If you are interested in parallel programming 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.


A Minimal Example with Function Call[edit]

Make a thread that prints numbers from 1-10 and waits a second between each print:

import threading
import time

def loop1_10():
    for i in range(1, 11):


A Minimal Example with Object[edit]

#!/usr/bin/env python

import threading
import time

class MyThread(threading.Thread):
    def run(self):
        print("{} started!".format(self.getName()))              # "Thread-x started!"
        time.sleep(1)                                      # Pretend to work for a second
        print("{} finished!".format(self.getName()))             # "Thread-x finished!"

if __name__ == '__main__':
    for x in range(4):                                     # Four times...
        mythread = MyThread(name = "Thread-{}".format(x + 1))  # ...Instantiate a thread and pass a unique ID to it
        mythread.start()                                   # ...Start the thread
        time.sleep(.9)                                     # ...Wait 0.9 seconds before starting another

The output should be:

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

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.