在python中停止一个线程

时间:2014-07-19 21:14:05

标签: python multithreading

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"])

2 个答案:

答案 0 :(得分:2)

假设您想要在线程停止时中断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

答案 1 :(得分:0)

这是一个例子。我们启动一个完成所有工作的线程。两秒钟后,我们通过设置共享Event标志告诉它死亡。

工作线程通常在循环中运行,进行一些处理,然后检查标志。如果它已设置,则退出,否则线程会做更多的工作。

import time
from threading import *

class WorkerThread(Thread):
    def __init__(self, die_flag, *args, **kw):
        super(WorkerThread,self).__init__(*args, **kw)
        self.die_flag = die_flag

    def run(self):
        for num in range(3):
            if self.die_flag.is_set():
                print "{}: bye".format(
                    current_thread().name
                    )
                return
            print "{}: num={}".format(
                current_thread().name, num,
                )
            time.sleep(1)

flag = Event()

WorkerThread(name='whiskey', die_flag=flag).start()
time.sleep(2)

print '\nTELL WORKERS TO DIE'
flag.set()

print '\nWAITING FOR WORKERS'
for thread in enumerate():
    if thread != current_thread():
        print thread.name,
        thread.join()
    print

输出

whiskey: num=0
whiskey: num=1

TELL WORKERS TO DIE

WAITING FOR WORKERS

whiskey whiskey: bye