为什么我的Python线程没有终止?

时间:2018-07-11 13:33:48

标签: python python-3.x multithreading terminate

在以下测试脚本中,我设置了一个生成两个ChildThreads的ParentThread。我希望能够正常终止所有线程,但似乎不成功。

from threading import Thread, Event
from time import sleep
class ParentWorker(Thread):

    def __init__(self, name, child1, child2):
        Thread.__init__(self)
        self.name = name
        self.stopper = Event()
        self.child1 = child1
        self.child2 = child2

    def stop_running(self):
        self.stopper.set()

    def start_engine(self):
        self.child1.start()
        self.child2.start()
        self.start()

    def stop_engine(self):
        self.child1.stop_running()
        self.child2.stop_running()
        self.stop_running()

    def run(self):
        while not self.stopper.is_set():
            print('{} is running!'.format(self.name))


class ChildWorker(Thread):

    def __init__(self, name):
        Thread.__init__(self)
        self.name = name
        self.stopper = Event()

    def stop_running(self):
        self.stopper.set()

    def run(self):
        while not self.stopper.is_set():
            print('{} is running!'.format(self.name))


if __name__ == '__main__':
    c1 = ChildWorker('child1')
    c2 = ChildWorker('child2')

    p = ParentWorker('parent', c1, c2)

    p.start_engine()
    sleep(10)

    p.stop_running()

    print('{} is_alive = {}'.format(c1.name, c1.is_alive()))
    print('{} is_alive = {}'.format(c2.name, c2.is_alive()))
    print('{} is_alive = {}'.format(p.name, p.is_alive()))

    print('attempting join on c1')
    c1.join()
    print('attempting join on c2')
    c2.join()
    print('attempting join on p')
    p.join()

    print('{} is_alive = {}'.format(c1.name, c1.is_alive()))
    print('{} is_alive = {}'.format(c2.name, c2.is_alive()))
    print('{} is_alive = {}'.format(p.name, p.is_alive()))

主线程似乎在p.start_engine()行之后停止运行,因此其他线程将永远运行。

为什么这样行事?主线程在完成之前死亡的原因是什么?

有什么想法吗?

0 个答案:

没有答案