代码之家  ›  专栏  ›  技术社区  ›  qwerty_so Rainier Wolfcastle

系统命令未并行运行的线程

  •  1
  • qwerty_so Rainier Wolfcastle  · 技术社区  · 4 年前

    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)一起使用。

    0 回复  |  直到 4 年前
        1
  •  3
  •   Daniel McLaury    4 年前

    我怀疑这里的问题是Python的全局解释器锁(GIL)。特别是我猜 os.system t1 ,GIL锁定,直到命令返回才解锁,防止 t2 运行任何python代码。

    os.system(self.cmd)
    

    具有

    subprocess.Popen(['bash', '-c', self.cmd])
    

    import subprocess
    
    subprocess.Popen(['bash', '-c', "afplay /System/Library/Sounds/Tink.aiff"])
    subprocess.Popen(['bash', '-c', "afplay /System/Library/Sounds/Ping.aiff"])