当前位置:   article > 正文

python threading中的thread开始和停止_python threading模块启动和停止

python threading模块启动和停止

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

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

  1. import threading
  2. import time
  3. class Concur(threading.Thread):
  4. def __init__(self):
  5. super(Concur, self).__init__()
  6. self.iterations = 0
  7. self.daemon = True # Allow main to exit even if still running.
  8. self.paused = True # Start out paused.
  9. self.state = threading.Condition()
  10. def run(self):
  11. while True:
  12. with self.state: # 在该条件下操作
  13. plt.figure(figsize=(4, 4)) # 一些操作
  14. plt.ion()
  15. plt.axis('off') # 不需要坐标轴
  16. plt.imshow(self._img_qr)
  17. while self._pause:
  18. plt.pause(0.05)
  19. plt.ioff() # 必须和plt.ion()配合使用,如果不加ioff会出问题
  20. if self.paused:
  21. self.state.wait() # Block execution until notified.
  22. def resume(self): # 用来恢复/启动run
  23. with self.state: # 在该条件下操作
  24. self.paused = False
  25. self.state.notify() # Unblock self if waiting.
  26. def pause(self): # 用来暂停run
  27. with self.state: # 在该条件下操作
  28. self.paused = True # Block self.
'
运行

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

 

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/818274
推荐阅读
相关标签
  

闽ICP备14008679号