Creating Threads in Python with _thread Module

Learn how to create new threads in Python using the _thread module and its start_new_thread() function. Review the syntax for initiating a new thread, including specifying the function to run, its arguments, and optional keyword arguments.



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

Syntax

Here is the syntax to create a new thread:

Syntax

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

This function starts a new thread and returns its identifier.

Parameters
  • function − The new thread starts running and calls the specified function.
  • args and kwargs − Arguments to be passed to the function.
Example

Here is an example of creating a thread:

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
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
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 
    while True:
KeyboardInterrupt