python threading中的thread开始和停止

转载:https://blog.csdn.net/ygfrancois/article/details/85265955

1. python threading.Thread只能使用一次start(), 否则会报RuntimeError

2. python threading.Thread无法kill,但是可以用threading.Condition()来控制线程的启动和停止

import threading
import time
 
class Concur(threading.Thread):
    def __init__(self):
        super(Concur, self).__init__()
        self.iterations = 0
        self.daemon = True  # Allow main to exit even if still running.
        self.paused = True  # Start out paused.
        self.state = threading.Condition()
 
    def run(self):
        while True:
            with self.state:  # 在该条件下操作
                plt.figure(figsize=(4, 4))  # 一些操作
                plt.ion()
                plt.axis('off')  # 不需要坐标轴
                plt.imshow(self._img_qr)
                while self._pause:
                    plt.pause(0.05)
                plt.ioff()  # 必须和plt.ion()配合使用,如果不加ioff会出问题
 
                if self.paused:
                    self.state.wait()  # Block execution until notified.
 
    def resume(self):  # 用来恢复/启动run
        with self.state:  # 在该条件下操作
            self.paused = False
            self.state.notify()  # Unblock self if waiting.
 
    def pause(self):  # 用来暂停run
        with self.state:  # 在该条件下操作
            self.paused = True  # Block self.

 

该线程start之后,可以调用resume来恢复启动run(开始因为self.paused=True,所以状态进入等待暂停状态),如果想暂停线程,调用pause即可。

 

参考:https://stackoverflow.com/questions/15729498/how-to-start-and-stop-thread
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值