How to Thread in Python
In computer science, a thread is a context for program execution. A multithreaded application has multiple threads that execute on their own, unless the programmer forces explicit synchronization between given threads. A thread is lightweight and efficient in its use of computer resources; unlike a process, no separate memory address space needs to be created for a thread. In particular, you can write multithreaded Python applications by using primitives defined as part of the standard library.
Instructions
-
-
1
Include the following lines at the beginning of your Python code:
import thread
import threading
-
2
Define a separate function to encapsulate the code that the new thread will run, as in the following sample code:
import time
def myThreadFunction(timeToWait):
print 'Thread about to wait '+str(timeToWait)+' seconds."
time.sleep(timeToWait)
print 'Thread finished waiting '+str(timeToWait)+' seconds."
The sample code will wait for "timeToWait" seconds, announcing the beginning and end of that time interval.
-
-
3
Create the thread as in the following sample code:
thread.start_new_thread(myThreadFunction, (10))
The first argument to the library function "thread.start_new_thread()" is the name of the function encapsulating the thread's code; the second argument is a tuple with whatever parameters that function needs. For the example, the tuple has a single integer element -- the number of seconds we want the thread to wait before exiting.
-
1