Python - 建立執行緒



在 Python 中建立執行緒涉及在程式中啟動一個單獨的執行流,允許多個操作併發執行。這對於同時執行任務特別有用,例如並行處理各種 I/O 操作。

Python 提供多種建立和管理執行緒的方法。

  • 通常建議使用threading模組建立和管理執行緒,因為它具有更高級別的介面和附加功能。

  • 另一方面,_thread模組提供了一種更簡單、更低階的建立和管理執行緒的方法,這對於簡單的、低開銷的執行緒任務很有用。

在本教程中,您將學習使用不同的方法在 Python 中建立執行緒的基礎知識。我們將介紹使用函式建立執行緒、從 threading 模組擴充套件 Thread 類以及使用 _thread 模組。

使用函式建立執行緒

您可以使用threading模組中的Thread類來建立執行緒。在這種方法中,您可以透過簡單地將函式傳遞給 Thread 物件來建立執行緒。以下是啟動新執行緒的步驟:

  • 定義執行緒要執行的函式。
  • 使用 Thread 類建立一個 Thread 物件,傳遞目標函式及其引數。
  • 呼叫 Thread 物件上的 start 方法以開始執行。
  • 可選地,呼叫 join 方法以等待執行緒完成,然後再繼續執行。

示例

以下示例演示了在 Python 中使用執行緒進行併發執行。它建立並啟動多個執行緒,這些執行緒透過在Thread類中指定使用者定義的函式作為目標來併發執行不同的任務。

from threading import Thread

def 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()

執行上述程式後,將產生以下結果:

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

透過擴充套件 Thread 類建立執行緒

建立執行緒的另一種方法是擴充套件 Thread 類。此方法涉及定義一個從 Thread 繼承並覆蓋其 __init__ 和 run 方法的新類。以下是啟動新執行緒的步驟:

  • 定義 Thread 類的新的子類。
  • 覆蓋 __init__ 方法以新增附加引數。
  • 覆蓋 run 方法以實現執行緒的行為。

示例

此示例演示如何使用自定義 MyThread 類建立和管理多個執行緒,該類擴充套件了 Python 中的threading.Thread類。

import threading
import time

exitFlag = 0

class 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 threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Start new Threads
thread1.start()
thread2.start()
print ("Exiting Main Thread")

執行上述程式碼後,將產生以下結果:

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

使用 start_new_thread() 函式建立執行緒

_thread 模組中包含的start_new_thread()函式用於在正在執行的程式中建立一個新執行緒。此模組提供了一種低階執行緒方法。它更簡單,但不具備 threading 模組提供的一些高階功能。

以下是 _thread.start_new_thread() 函式的語法

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

此函式啟動一個新執行緒並返回其識別符號。function引數指定新執行緒將執行的函式。此函式所需的任何引數都可以使用 args 和 kwargs 傳遞。

示例

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
   
thread_task("test", 0.3)

它將產生以下輸出

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

程式進入無限迴圈。您需要按ctrl-c停止。

廣告