import threading import ctypes import logging import sys def test_async(): logger = logging.getLogger() logger.setLevel(logging.DEBUG) iterations = 200 sys.setswitchinterval(0.00001) def my_async(thread_num): tid = threading.current_thread().ident for i in range(iterations): logger.info(f"Thread num {thread_num}, id: {tid}, run number {i}") if i > 2 and thread_num % i == 0: exception_thread = threading.Timer(0.1, raise_exception, args=[thread_num, i, tid]) exception_thread.start() threads = [threading.Thread(target=my_async, args=[i + 1]) for i in range(iterations)] def raise_exception(thread_num, i, tid): print(f"Raising exception in thread num {thread_num}, id: {tid}, run number {i}") ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(Exception)) [thread.setDaemon(True) for thread in threads] [thread.start() for thread in threads] [thread.join() for thread in threads] print("This will not print")