Python - Creating a Thread



The start_new_thread() function included in the _thread module is used to create a new thread in the running program.

Syntax

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

This function starts a new thread and returns its identifier.

Parameters

  • function − Newly created thread starts running and calls the specified function. If any arguments are required for the function, that may be passed as parameters args and kwargs.

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:\Users\user\example.py", line 17, in <module>
  while True:
KeyboardInterrupt

The program goes in an infinite loop. You will have to press "ctrl-c" to stop.

Advertisements