codescracker


python

Python Multithreading



« Previous Tutorial Next Tutorial »


Running several threads is similar to running several different programs concurrently. A thread has a beginning, an execution sequence, and conclusion. It has basically an instruction pointer, keeps track of where within its context it is currently running.

To spawn another tread, you need to call this method available in the python thread module:

thread.start_new_thread(function, args[, kwargs])

The above method call enables a fast and an efficient way to create new threads in both the platform, Linux and Windows.

Python Multithreading Example

Here is an example program, demonstrates the concept and use of multithreading in python:

# Python Multithreading - Example Program 

import thread
import time

def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print("%s: %s" % (threadName, time.ctime(time.time())))

try:
   thread.start_new_thread(print_time, ("Thread-1", 2,))
   thread.start_new_thread(print_time, ("Thread-2", 4,))
except:
   print("Error: unable to start thread");

while 1:
   pass

Now when the above code is executed, it will produce the following result:

Thread-1: Sat Jan 24 18:36:17 2015
Thread-1: Sat Jan 24 18:36:19 2015
Thread-2: Sat Jan 24 18:36:19 2015
Thread-1: Sat Jan 24 18:36:21 2015
Thread-2: Sat Jan 24 18:36:23 2015
Thread-1: Sat Jan 24 18:36:23 2015
Thread-1: Sat Jan 24 18:36:25 2015
Thread-2: Sat Jan 24 18:36:27 2015
Thread-2: Sat Jan 24 18:36:31 2015
Thread-2: Sat Jan 24 18:36:35 2015

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test