Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python - Creating a Thread



Creating a thread in Python involves initiating a separate flow of execution within a program, allowing multiple operations to run concurrently. This is particularly useful for performing tasks simultaneously, such as handling various I/O operations in parallel.

Python provides multiple ways to create and manage threads.

  • Creating a thread using thethreading module is generally recommended due to its higher-level interface and additional functionalities.

  • On the other hand, the_thread module offers a simpler, lower-level approach to create and manage threads, which can be useful for straightforward, low-overhead threading tasks.

In this tutorial, you will learn the basics of creating threads in Python using different approaches. We will cover creating threads using functions, extending the Thread class from the threading module, and utilizing the _thread module.

Creating Threads with Functions

You can create threads by using theThread class from thethreading module. In this approach, you can create a thread by simply passing a function to the Thread object. Here are the steps to start a new thread −

  • Define a function that you want the thread to execute.
  • Create a Thread object using the Thread class, passing the target function and its arguments.
  • Call the start method on the Thread object to begin execution.
  • Optionally, call the join method to wait for the thread to complete before proceeding.

Example

The following example demonstrates concurrent execution using threads in Python. It creates and starts multiple threads that execute different tasks concurrently by specifying user-defined functions as targets within theThread class.

from threading import Threaddef addition_of_numbers(x, y):   result = x + y   print('Addition of {} + {} = {}'.format(x, y, result))def cube_number(i):   result = i ** 3   print('Cube of {} = {}'.format(i, result))def basic_function():   print("Basic function is running concurrently...")Thread(target=addition_of_numbers, args=(2, 4)).start()  Thread(target=cube_number, args=(4,)).start() Thread(target=basic_function).start()

On executing the above program, it will produces the following result −

Addition of 2 + 4 = 6Cube of 4 = 64Basic function is running concurrently...

Creating Threads by Extending the Thread Class

Another approach to creating a thread is by extending the Thread class. This approach involves defining a new class that inherits from Thread and overriding its __init__ and run methods. Here are the steps to start a new thread −

  • Define a new subclass of the Thread class.
  • Override the __init__ method to add additional arguments.
  • Override the run method to implement the thread's behavior.

Example

This example demonstrates how to create and manage multiple threads using a custom MyThread class that extends thethreading.Thread class in Python.

import threadingimport timeexitFlag = 0class myThread (threading.Thread):   def __init__(self, threadID, name, counter):      threading.Thread.__init__(self)      self.threadID = threadID      self.name = name      self.counter = counter   def run(self):      print ("Starting " + self.name)      print_time(self.name, 5, self.counter)      print ("Exiting " + self.name)def print_time(threadName, counter, delay):   while counter:      if exitFlag:         threadName.exit()      time.sleep(delay)      print ("%s: %s" % (threadName, time.ctime(time.time())))      counter -= 1# Create new threadsthread1 = myThread(1, "Thread-1", 1)thread2 = myThread(2, "Thread-2", 2)# Start new Threadsthread1.start()thread2.start()print ("Exiting Main Thread")

When the above code is executed, it produces the following result −

Starting Thread-1Starting Thread-2Exiting Main ThreadThread-1: Mon Jun 24 16:38:10 2024Thread-2: Mon Jun 24 16:38:11 2024Thread-1: Mon Jun 24 16:38:11 2024Thread-1: Mon Jun 24 16:38:12 2024Thread-2: Mon Jun 24 16:38:13 2024Thread-1: Mon Jun 24 16:38:13 2024Thread-1: Mon Jun 24 16:38:14 2024Exiting Thread-1Thread-2: Mon Jun 24 16:38:15 2024Thread-2: Mon Jun 24 16:38:17 2024Thread-2: Mon Jun 24 16:38:19 2024Exiting Thread-2

Creating Threads using start_new_thread() Function

Thestart_new_thread() function included in the_thread module is used to create a new thread in the running program. This module offers a low-level approach to threading. It is simpler but does not have some of the advanced features provided by the threading module.

Here is the syntax of the _thread.start_new_thread() Function

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

This function starts a new thread and returns its identifier. Thefunction parameter specifies the function that the new thread will execute. Any arguments required by this function can be passed using args and kwargs.

Example

import _threadimport time# Define a function for the threaddef thread_task( threadName, delay):   for count in range(1, 6):      time.sleep(delay)      print ("Thread name: {} Count: {}".format ( threadName, count ))# Create two threads as followstry:    _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   thread_task("test", 0.3)

It will produce the followingoutput

Thread name: Thread-1 Count: 1Thread name: Thread-2 Count: 1Thread name: Thread-1 Count: 2Thread name: Thread-1 Count: 3Thread name: Thread-2 Count: 2Thread name: Thread-1 Count: 4Thread name: Thread-1 Count: 5Thread name: Thread-2 Count: 3Thread name: Thread-2 Count: 4Thread name: Thread-2 Count: 5Traceback (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 pressctrl-c to stop.

Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp