Python多线程-如何停止循环线程?

四个解决方案

1.定义一个自带变量(初始值为True)

import threading
import time
class Tutu(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.threadLock = True

    def do_run(self):
        while self.threadLock:
            print("我在运行")
            time.sleep(1)

if __name__ == "__main__":
        # global threadLock
        tu = Tutu()
        t = threading.Thread(target=tu.do_run,name='Thread-110')
        t.start()
        time.sleep(5)
        tu.threadLock = False
        t.join()
        print('结束')

输出以下结果:

我在运行
我在运行
我在运行
我在运行
我在运行
结束

2.螺纹可停止功能

可以将函数修改为允许以下操作,而不是将threading.Thread分为子类:停下一个标志。
我们需要一个运行函数可访问的对象,将标志设置为停止运行。
我们可以使用doit对象。

import threading
import time

```javascript
def doit(arg):
    t = threading.currentThread()
    while getattr(t, "do_run", True):
        print ("working on %s" % arg)
        time.sleep(1)
    print("Stopping as you wish.")


def main():
    t = threading.Thread(target=doit, args=("task",))
    t.start()
    time.sleep(5)
    t.do_run = False
    t.join()

if __name__ == "__main__":
    main()

诀窍在于,正在运行的线程可以附加其他属性。 解决方案构建根据假设:
线程具有属性“ do_run”,默认值为doit
驱动父进程可以将属性“ do_run”分配给启动线程doit。
运行代码,我们得到以下输出:

$ python stopthread.py                                                        
working on task
working on task
working on task
working on task
working on task
Stopping as you wish.

3.药丸杀死-使用事件

其他替代方法是使用doit作为函数参数。 是通过默认值为main,但外部进程可以“对其进行设置”(为True),并且功能可以使用wait(timeout)函数了解它。
我们可以将doit的超时时间设置为零,但也可以将其用作睡眠计时器(以下使用)。

def doit(stop_event, arg):
    while not stop_event.wait(1):
        print ("working on %s" % arg)
    print("Stopping as you wish.")


def main():
    pill2kill = threading.Event()
    t = threading.Thread(target=doit, args=(pill2kill, "task"))
    t.start()
    time.sleep(5)
    pill2kill.set()
    t.join()

ps:我在Python 3.6中尝试过。 doit阻止事件(以及while循环),直到释放为止。 它不返回布尔值。 而是使用main。

4.用一颗药丸停止多线程

如果我们必须停止多个线程,则可以更好地看出使用药丸杀死的优势一次,因为一粒药将对所有人有效。
doit完全不会更改,只有main处理线程的方式有所不同。

def main():
    pill2kill = threading.Event()
    tasks = ["task ONE", "task TWO", "task THREE"]

    def thread_gen(pill2kill, tasks):
        for task in tasks:
            t = threading.Thread(target=doit, args=(pill2kill, task))
            yield t

    threads = list(thread_gen(pill2kill, tasks))
    for thread in threads:
        thread.start()
    time.sleep(5)
    pill2kill.set()
    for thread in threads:
        thread.join()

更多详情可参考:
链接: link.

  • 6
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值