Jun 2024
This commit is contained in:
27
script/cpython/TestInterrupt.py
Normal file
27
script/cpython/TestInterrupt.py
Normal file
@@ -0,0 +1,27 @@
|
||||
import threading
|
||||
from threading import Thread
|
||||
from _thread import interrupt_main
|
||||
import sys
|
||||
|
||||
# task executed in a new thread
|
||||
def task():
|
||||
# block for a moment
|
||||
sleep(3)
|
||||
# interrupt the main thread
|
||||
print('Interrupting main thread now')
|
||||
interrupt_main()
|
||||
|
||||
# start the new thread
|
||||
thread = Thread(target=task)
|
||||
thread.start()
|
||||
|
||||
print(threading.current_thread() == threading.main_thread())
|
||||
# handle being interrupted
|
||||
try:
|
||||
# wait around
|
||||
while True:
|
||||
print('Main thread waiting...')
|
||||
sleep(0.5)
|
||||
except KeyboardInterrupt:
|
||||
# terminate main thread
|
||||
print('Main interrupted! Exiting.')
|
||||
Reference in New Issue
Block a user