gpt4 book ai didi

python - 停止Python中的线程

转载 作者:行者123 更新时间:2023-12-01 05:06:51 28 4
gpt4 key购买 nike

Python中有没有办法停止线程?我有一个 GUI,其方法可以播放 10 秒音频文件并连续向 GUI 窗口发送信息

我使用多线程,因为我不希望 GUI 在文件播放时卡住。我可以使用当前代码停止线程,但需要一段时间

我的代码看起来像这样:

class MyThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""

def __init__(self, *args, **kwargs):
super(MyThread, self).__init__(*args, **kwargs)
self._stop = threading.Event()

def stop(self):
self._stop.set()

def stopped(self):
return self._stop.isSet()


class Myplayer:

// GUI CODE


def play_button(self, widget):
self.mythread = MyThread(target=self.practice)
self.mythread.start()

def stop_button(self, widget):
if self.mythead.IsAlive:
self.self.stop()



def mplayer(self):
while not self.mythread.stopped:
gobject.idle_add(self.insert_text, "\nPlaying a new file")
subprocess.call(["timidity", "myfile.mid"])

最佳答案

假设您想在线程停止时中断正在播放的 midi 文件,则可以使用 Popen 而不是 call 更快地停止线程,然后循环等待进程完成或停止请求传入:

class MyThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""

def __init__(self, *args, **kwargs):
super(MyThread, self).__init__(*args, **kwargs)
self._stop = threading.Event()

def stop(self):
self._stop.set()

def stopped(self):
return self._stop.isSet()

def run(self):
while not self.stopped:
gobject.idle_add(self.insert_text, "\nPlaying a new file")
p = subprocess.Popen(["timidity", "myfile.mid"])
while p.poll() is None: # This will loop until the process has exited.
if self.stopped:
# Someone set the stop flag. Kill the process and exit
p.terminate()
p.join()
return
time.sleep(.1) # Sleep briefly so we don't hog CPU cycles

关于python - 停止Python中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24845025/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com