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.


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

This function starts a new thread and returns its identifier.


  • 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.


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

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

while True:

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\", line 17, in <module>
  while True:

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

Kickstart Your Career

Get certified by completing the course

Get Started