Python Programming/Threading
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.
Examples
[edit | edit source]A Minimal Example with Function Call
[edit | edit source]Make a thread that prints numbers from 1-10 and waits a second between each print:
importthreadingimporttimedefloop1_10():foriinrange(1,11):time.sleep(1)print(i)threading.Thread(target=loop1_10).start()
A Minimal Example with Object
[edit | edit source]#!/usr/bin/env pythonimportthreadingimporttimeclassMyThread(threading.Thread):defrun(self):# Default called function with mythread.start()print("{} started!".format(self.getName()))# "Thread-x started!"time.sleep(1)# Pretend to work for a secondprint("{} finished!".format(self.getName()))# "Thread-x finished!"defmain():forxinrange(4):# Four times...mythread=MyThread(name="Thread-{}".format(x))# ...Instantiate a thread and pass a unique ID to itmythread.start()# ...Start the thread, run method will be invokedtime.sleep(.9)# ...Wait 0.9 seconds before starting anotherif__name__=='__main__':main()
The output looks like this:
Thread-0 started! Thread-1 started! Thread-0 finished! Thread-2 started! Thread-1 finished! Thread-3 started! Thread-2 finished! Thread-3 finished!