Multithreaded programming in Python
Running several threads is similar to running several different programs concurrently, but with the following benefits:
- Multiple threads within a process share the same data space with the main thread and can therefore share information or communicate with each other more easily than if they were separate processes. - Threads sometimes called light-weight processes and they do not require much memory overhead; they are cheaper than processes.
A thread has a beginning, an execution sequence, and a conclusion. It has an instruction pointer that keeps track of where within its context it is currently running.
- It can be pre-empted (interrupted) - It can temporarily be put on hold (also known as sleeping) while other threads are running - this is called yielding.
Starting a New Thread
To spawn another thread, you need to call following method available in thread module −
thread.start_new_thread ( function, args[, kwargs] )
This method call enables a fast and efficient way to create new threads in both Linux and Windows. The method call returns immediately and the child thread starts and calls function with the passed list of args. When function returns, the thread terminates. Here, args is a tuple of arguments; use an empty tuple to call function without passing any arguments. kwargs is an optional dictionary of keyword arguments.
Example
1 #!/usr/bin/python 2 3 import thread 4 import time 5 6 # Define a function for the thread 7 def print_time( threadName, delay): 8 count = 0 9 while count < 5: 10 time.sleep(delay) 11 count += 1 12 print "%s: %s" % ( threadName, time.ctime(time.time()) ) 13 14 # Create two threads as follows 15 try: 16 thread.start_new_thread( print_time, ("Thread-1", 2, ) ) 17 thread.start_new_thread( print_time, ("Thread-2", 4, ) ) 18 except: 19 print "Error: unable to start thread" 20 21 while 1: 22 pass