Python 3 中的多線程

線程是獨立執行或由操作系統調度的程序或進程的最小單元。在計算機系統中,操作系統通過將進程劃分為線程來實現多任務處理。線程是一個輕量級的進程,它確保進程在系統上獨立執行。在 Python 3 中,當多個處理器在一個程序上運行時,每個處理器同時運行以分別執行其任務。

Python 多線程

多線程是 Python 編程中的一種線程技術,通過在 CPU 的幫助下在線程之間快速切換來並發運行多個線程(稱為上下文切換)。此外,它允許與進程內的主線程共享其數據空間,這比單獨的進程更容易與其他線程共享信息和通信。多線程旨在同時執行多個任務,這提高了性能、速度並改善了應用的呈現。

注意:Python 全局解釋器鎖(GIL)允許一次運行一個線程,即使機器有多個處理器。

Python 中多線程的好處

以下是用 Python 創建多線程應用的好處,如下所示:

  1. 它保證了計算機系統資源的有效利用。
  2. 多線程應用響應速度更快。
  3. 它與子線程(子線程)共享資源及其狀態,這使得它更加經濟。
  4. 由於相似性,它使多進程器體系結構更加有效。
  5. 它通過同時執行多個線程來節省時間。
  6. 系統不需要太多內存來存儲多個線程。

Python 中何時使用多線程?

這是一種非常有用的技術,可以節省時間並提高應用的性能。多線程允許程序員將應用任務劃分為子任務,並在程序中同時運行它們。它允許線程與同一個處理器通信並共享資源,如文件、數據和內存。此外,它提高了用戶繼續運行程序的響應能力,即使應用的一部分太長或被阻塞。

Python 中如何實現多線程?

Python 中用於處理線程的多線程主要有兩個模塊。

  1. 線程模塊
  2. 線程模塊

線程模塊

從 Python 3 開始,指定為過時,只能用支持向後兼容的 _thread 訪問。

語法:


thread.start_new_thread ( function_name, args[, kwargs] )

要在 Python 中實現線程模塊,我們需要導入一個線程模塊,然後通過用變量設置目標來定義一個執行某個動作的函數。

螺紋 py


import thread # import the thread module
import time # import time module

def cal_sqre(num): # define the cal_sqre function
    print(" Calculate the square root of the given number")
    for n in num: 
        time.sleep(0.3) # at each iteration it waits for 0.3 time
        print(' Square is : ', n * n)

def cal_cube(num): # define the cal_cube() function
    print(" Calculate the cube of  the given number")
    for n in num: 
        time.sleep(0.3) # at each iteration it waits for 0.3 time
        print(" Cube is : ", n * n *n)

arr = [4, 5, 6, 7, 2] # given array

t1 = time.time() # get total time to execute the functions
cal_sqre(arr) # call cal_sqre() function
cal_cube(arr) # call cal_cube() function

print(" Total time taken by threads is :", time.time() - t1) # print the total time

輸出:

Calculate the square root of the given number
 Square is:  16
 Square is:  25
 Square is:  36
 Square is:  49
 Square is:  4
 Calculate the cube of the given number
 Cube is:  64
 Cube is:  125
 Cube is:  216
 Cube is:  343
 Cube is:  8
 Total time taken by threads is: 3.005793809890747

線程模塊

線程模塊是多線程的高級實現,用於在 Python 中部署應用。要使用多線程,我們需要在 Python 程序中導入線程模塊。

螺紋分類方法

| 方法 | 描述 |
| start() | start()方法用於啟動線程的活動。它只為每個線程調用一次,這樣線程的執行就可以開始了。 |
| 運行() | run()方法用於定義線程的活動,並且可以被擴展線程類的類覆蓋。 |
| join() | join()方法用於阻止另一個代碼的執行,直到線程終止。 |

按照下面給出的步驟在 Python 多線程中實現線程模塊:

1。導入穿線模塊

通過導入穿線模塊創建新的穿線,如圖所示。

語法:


import threading

一個線程模塊由一個線程類組成,這個類被實例化來創建一個 Python 線程。

2。線程參數的聲明:它包含目標函數、參數和 kwargs 作為 Thread() 類中的參數。

  • 目標:定義線程執行的函數名。
  • 參數:定義傳遞給目標函數名的參數。

例如:


import threading
def print_hello(n):
print("Hello, how old are you ", n)
t1 = threading.Thread( target = print_hello, args =(18, ))

在上面的代碼中,我們調用了 print_hello() 函數作為目標參數。 print_hello() 包含一個參數 n ,傳遞給 args 參數。

3。啟動新線程:要在 Python 多線程中啟動線程,請調用線程類的對象。對於每個線程對象,可以調用 start()方法一次;否則,它會引發異常錯誤。

語法:


t1.start()
t2.start()

4。Join 方法:是線程類中使用的 join()方法,用於暫停主線程的執行,等待線程對象的完全執行。線程對象完成後,開始執行 Python 中的主線程。

連接方法. py


import threading
def print_hello(n):
    Print("Hello, how old are you? ", n)
T1 = threading.Thread( target = print_hello, args = (20, ))
T1.start()
T1.join()
Print("Thank you")

輸出:

Hello, how old are you? 20
Thank you

執行上述程序時,join()方法會暫停主線程的執行,並等待直到線程 t1 完全執行。一旦 t1 成功執行,主線程就開始執行。

注意:如果我們不使用 join()方法,解釋器可以在 Python 程序中執行任何 print 語句。一般來說,它執行第一個 print 語句,因為解釋器從程序開始就執行代碼行。

5。在 Python 中同步線程

這是一種線程同步機制,確保沒有兩個線程可以同時執行程序中的特定段來訪問共享資源。這種情況可以稱為臨界區。我們使用競爭條件來避免臨界區條件,在臨界區條件中,兩個線程不會同時訪問資源。

讓我們編寫一個程序來使用 Python 多線程中的線程模塊。

穿線. py


import time # import time module
import threading
from threading import *
def cal_sqre(num): # define a square calculating function
    print(" Calculate the square root of the given number")
    for n in num: # Use for loop 
        time.sleep(0.3) # at each iteration it waits for 0.3 time
        print(' Square is : ', n * n)

def cal_cube(num): # define a cube calculating function
    print(" Calculate the cube of  the given number")
    for n in num: # for loop
        time.sleep(0.3) # at each iteration it waits for 0.3 time
        print(" Cube is : ", n * n *n)

ar = [4, 5, 6, 7, 2] # given array

t = time.time() # get total time to execute the functions
#cal_cube(ar)
#cal_sqre(ar)
th1 = threading.Thread(target=cal_sqre, args=(ar, ))
th2 = threading.Thread(target=cal_cube, args=(ar, ))
th1.start()
th2.start()
th1.join()
th2.join()
print(" Total time taking by threads is :", time.time() - t) # print the total time
print(" Again executing the main thread")
print(" Thread 1 and Thread 2 have finished their execution.")

輸出:

Calculate the square root of the given number
 Calculate the cube of the given number
 Square is:  16
 Cube is:  64
 Square is:  25
 Cube is:  125
 Square is:  36
 Cube is:  216
 Square is:  49
 Cube is:  343
 Square is:  4
 Cube is:  8
 Total time taken by threads is: 1.5140972137451172
 Again executing the main thread
 Thread 1 and Thread 2 have finished their execution.

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/270458.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-16 13:37
下一篇 2024-12-16 13:37

相關推薦

  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29

發表回復

登錄後才能評論