Creating Threads in Python: Concurrent Execution for Parallel Tasks

thumb_up 1  ·  sell Python thread creation, Creating threads for parallel tasks in Python, Multithreading in Python code

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.

 

 

The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.

Was this answer helpful?

Related Articles

description

Exploring Python's Key Characteristic

Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language. This tutorial will list down some of…

arrow_forward
description

Comparing Python and C++

Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this…

arrow_forward
description

Creating a Python Hello World Program

This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of…

arrow_forward
description

Python's Versatile Application Domains

Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few…

arrow_forward
description

Understanding the Python Interpreter

Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the…

arrow_forward
arrow_back « Back