線程是獨立執行或由操作系統調度的程序或進程的最小單元。在計算機系統中,操作系統通過將進程劃分為線程來實現多任務處理。線程是一個輕量級的進程,它確保進程在系統上獨立執行。在 Python 3 中,當多個處理器在一個程序上運行時,每個處理器同時運行以分別執行其任務。
Python 多線程
多線程是 Python 編程中的一種線程技術,通過在 CPU 的幫助下在線程之間快速切換來並發運行多個線程(稱為上下文切換)。此外,它允許與進程內的主線程共享其數據空間,這比單獨的進程更容易與其他線程共享信息和通信。多線程旨在同時執行多個任務,這提高了性能、速度並改善了應用的呈現。
注意:Python 全局解釋器鎖(GIL)允許一次運行一個線程,即使機器有多個處理器。
Python 中多線程的好處
以下是用 Python 創建多線程應用的好處,如下所示:
- 它保證了計算機系統資源的有效利用。
- 多線程應用響應速度更快。
- 它與子線程(子線程)共享資源及其狀態,這使得它更加經濟。
- 由於相似性,它使多進程器體系結構更加有效。
- 它通過同時執行多個線程來節省時間。
- 系統不需要太多內存來存儲多個線程。
Python 中何時使用多線程?
這是一種非常有用的技術,可以節省時間並提高應用的性能。多線程允許程序員將應用任務劃分為子任務,並在程序中同時運行它們。它允許線程與同一個處理器通信並共享資源,如文件、數據和內存。此外,它提高了用戶繼續運行程序的響應能力,即使應用的一部分太長或被阻塞。
Python 中如何實現多線程?
Python 中用於處理線程的多線程主要有兩個模塊。
- 線程模塊
- 線程模塊
線程模塊
從 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-tw/n/270458.html