Python thread 建立多執行緒用法與範例

本篇 ShengYu 將介紹如何使用 Python 來建立多執行緒 multithread,多執行緒 multithread 是很常會用到的程式技能,接下來介紹怎麼使用 python 3 的 threading 模組來建立執行緒吧。

以下的 Python thread 執行緒用法與範例將分為這幾部分,

  • Python 單執行緒到多執行緒的思維
  • Python 建立多個執行緒的範例
  • Python 撰寫多執行緒的注意事項

那我們開始吧!

Python 單執行緒到多執行緒的思維

原本寫程式只會單執行緒從頭寫到尾,例如單執行緒做了 ABC 三件事,總共花了 3 秒,但如果 ABC 三件事的內容是互相不影響的,那改成多執行緒的寫法,同時開 3 個執行緒分別去執行A、B和C的話,可能總共只需要 1 秒呢!這麼厲害的技巧一定要學囉,馬上來學習吧!

Python 建立多個執行緒的範例

下範例是使用 Python 3 的threading.Thread()建立了三個執行緒,每次的寫法都不太一樣,分別為去執行 print_hello()print_hellowrold()print_hi()
print_hello()函式裡很簡單地印出3次的 Hello,並且間隔0.5秒印一次,
print_hellowrold()函式是根據帶入一個參數n去印,需要注意的是在threading.Thread()args 是要傳入一個tuple, 而tuple只有一個元素的寫法為 args = (3,) 這樣,需要另外加個逗號,
print_hi()函式為兩個參數。

另外依據 time.sleep() 參數給入的秒數,time.sleep() 函式暫停執行當前的執行緒,
如果行程裡只有單一條執行緒的話,等同於暫停執行整個行程。

python3-create-thread.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import threading
import time

def print_hello():
for i in range(3):
time.sleep(0.5)
print("Hello " + str(i))

def print_hellowrold(n):
for i in range(n):
time.sleep(0.5)
print("Hello world "+ str(i))

def print_hi(n, interval):
for i in range(n):
time.sleep(interval)
print("Hi "+ str(i))

t1 = threading.Thread(target = print_hello)
t2 = threading.Thread(target = print_hellowrold, args = (3,))
t3 = threading.Thread(target = print_hi,
args = (3, 0.2))
t1.start()
t2.start()
t3.start()

輸出結果如下所示:

1
2
3
4
5
6
Hi
Hi
Hello
Hi
Hello
Hello

另外開執行緒也可以不取得回傳變數直接執行,例如threading.Thread(target = print_hello).start()這樣寫,

threading 的詳細細節請參考這裡

Python 撰寫多執行緒的注意事項

多執行緒程式比單執行緒程式難撰寫,也難以維護跟除錯,因為多執行緒間的資源共享,可能會造成以下這些問題:

  • Race condition (競爭情況/競爭條件/競爭危害)
  • 死結 Deadlock - 當一個執行緒在無窮等待一個鎖時。
  • Livelock
  • Starvation (餓死/飢餓) - 一個行程取得不到 CPU 時間來完成工作。

以上就是 Python thread 建立多執行緒用法與範例介紹,
如果你覺得我的文章寫得不錯、對你有幫助的話記得 Facebook 按讚支持一下!

其他參考
Use PyQt’s QThread to Prevent Freezing GUIs – Real Python
https://realpython.com/python-pyqt-qthread/

其它相關文章推薦
如果你想學習 Python 相關技術,可以參考看看下面的文章,
Python 新手入門教學懶人包
Python 取得鍵盤輸入 input
Python if else elif 用法教學與範例
Python for 迴圈
Python sort 排序
Python 讀檔,讀取 txt 文字檔
Python 字串分割 split
Python 取代字元或取代字串 replace