繁体   English   中英

线程未针对系统命令并行运行

[英]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.systemt1中调用时,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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM