[英]Threads not running in parallel for a system command
這是我的腳本
import threading
import os
class Say(threading.Thread):
def __init__(self, cmd):
super(Say, self).__init__()
self.cmd = cmd
def run(self):
os.system(self.cmd)
t1 = Say("afplay /System/Library/Sounds/Tink.aiff")
t2 = Say("afplay /System/Library/Sounds/Ping.aiff")
t1.start()
print("a")
t2.start()
print("b")
似乎兩個啟動都立即執行。 但是,這些聲音不是並行播放的,而是一個接一個地播放。
運行以下 shell 腳本時
afplay /System/Library/Sounds/Tink.aiff &
afplay /System/Library/Sounds/Ping.aiff &
兩種聲音同時播放。 是什么讓 Python 順序運行命令而不是並行運行?
我將 Big Sur 與標准 Python (2.7) 一起使用。
我懷疑這里的問題是 Python 的全局解釋器鎖 (GIL)。 特別是我猜測當os.system
在t1
中調用時,GIL 會鎖定並且在命令返回之前不會解鎖,從而阻止t2
運行任何 python 代碼。
如果我更換
os.system(self.cmd)
和
subprocess.Popen(['bash', '-c', self.cmd])
然后問題就消失了。
就此而言,由於您在任何情況下都在生成單獨的進程並且對它們的 output 什么都不做,因此創建所有這些線程是沒有意義的; 您可以通過將整個代碼示例替換為
import subprocess
subprocess.Popen(['bash', '-c', "afplay /System/Library/Sounds/Tink.aiff"])
subprocess.Popen(['bash', '-c', "afplay /System/Library/Sounds/Ping.aiff"])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.