Python threading interrupt sleep

偶尔善良 提交于 2019-12-18 09:00:43

问题


Is there a way in python to interrupt a thread when it's sleeping? (As we can do in java)

I am looking for something like that.

  import threading
  from time import sleep

  def f():
      print('started')
  try:
      sleep(100)
      print('finished')
  except SleepInterruptedException:
      print('interrupted')

t = threading.Thread(target=f)
t.start()

if input() == 'stop':
    t.interrupt()

The thread is sleeping for 100 seconds and if I type 'stop', it interrupts


回答1:


How about using condition objects: https://docs.python.org/2/library/threading.html#condition-objects

Instead of sleep() you use wait(timeout). To "interrupt" you call notify().




回答2:


The correct approach is to use threading.Event. For example:

import threading

e = threading.Event()
e.wait(timeout=100)   # instead of time.sleep(100)

In the other thread, you need to have access to e. You can interrupt the sleep by issuing:

e.set()

This will immediately interrupt the sleep. You can check the return value of e.wait to determine whether it's timed out or interrupted. For more information refer to the documentation: https://docs.python.org/3/library/threading.html#event-objects .



来源:https://stackoverflow.com/questions/38828578/python-threading-interrupt-sleep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!