Python thread creation

Creating Python Threads

Import the _thread module to create a new thread in the running program using the start_new_thread() function.

Syntax

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

This function starts a new thread and returns its identifier.

Parameters

  • function − The newly created thread starts running and calls the specified function. If the function requires arguments, they can be passed as the args and kwargs parameters.

Example

import _thread
import time
# Define a function for the thread
def thread_task( threadName, delay):
   for count in range(1, 6):
      time.sleep(delay)
      print ("Thread name: {} Count: {}".format ( threadName, count ))

# Create two threads as follows
try:
   _thread.start_new_thread( thread_task, ("Thread-1", 2, ) )
   _thread.start_new_thread( thread_task, ("Thread-2", 4, ) )
except:
   print ("Error: unable to start thread")

while True:
   pass

It will produce the following output

Thread name: Thread-1 Count: 1
Thread name: Thread-2 Count: 1
Thread name: Thread-1 Count: 2
Thread name: Thread-1 Count: 3
Thread name: Thread-2 Count: 2
Thread name: Thread-1 Count: 4
Thread name: Thread-1 Count: 5
Thread name: Thread-2 Count: 3
Thread name: Thread-2 Count: 4
Thread name: Thread-2 Count: 5
Traceback (most recent call last):
 File "C:Usersuserexample.py", line 17, in <module>
  while True:
KeyboardInterrupt

The program enters an infinite loop. You need to press “ctrl-c” to stop.

Leave a Reply

Your email address will not be published. Required fields are marked *