Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python threading interrupt sleep

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

like image 923
Vadim Volodin Avatar asked Aug 08 '16 11:08

Vadim Volodin


People also ask

Can thread sleep be interrupted?

A thread that is in the sleeping or waiting state can be interrupted with the help of the interrupt() method of Thread class.

How do you break a sleep in Python?

In most systems, Ctrl-C would interrupt the sleep. It certainly does on Unix and on Mac.

What does sleep 0 do in Python?

A thread can call Sleep(0) to relinquish its quantum, thereby reducing its share of the CPU. Note, however, that this does not guarantee that other threads will run.


2 Answers

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 .

like image 185
He Shiming Avatar answered Sep 23 '22 03:09

He Shiming


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().

like image 34
Eirik M Avatar answered Sep 26 '22 03:09

Eirik M