Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

thread.interrupt_main() doesn't work when waiting for input

I've read about this technique to timeout blocking IO operations, the problem is that it doesn't seem to work. for example:

import thread, threading
   
def read_timeout(prompt, timeout=10.0):
    timer = threading.Timer(timeout, thread.interrupt_main)
    s = ''
    timer.start()
    
    try:
        s = raw_input(prompt)
    except KeyboardInterrupt:
        print 'operation timed out.'
        
    timer.cancel()
    return s
    
s = read_timeout('enter input: ')

if s:
    print 'you entered: %s' % s

this won't interrupt the main thread until raw_input() returns. Any help is appreciated.

Update:

Using os.kill(os.getpid(), signal.SIGINT) instead of thread.interrupt_main() seems to work (at least on Linux, which doesn't give me the portability I initially wanted). However, I'm still wondering why the code above doesn't work.

like image 592
Amr Avatar asked May 30 '26 06:05

Amr


1 Answers

According to the latest doc of the API: https://docs.python.org/3/library/_thread.html#thread.interrupt_main

This does not emit the corresponding signal but schedules a call to the associated handler (if it exists).

And the call is performed after the current blocking call in the main thread.

On the other hand, the os.kill solution mentioned in the update immediately emits a signal to the main thread.

Sorry that it's been quite a while since the question was raised, but hopefully it still helps.

like image 91
caocao Avatar answered Jun 01 '26 19:06

caocao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!