D
D
dadasay2019-08-27 16:59:03
SQL
dadasay, 2019-08-27 16:59:03

Can I throw an exception from thread A on thread B?

For example, the following code is executed in thread B:
....
While True:
b = 1
....
and I need to throw an exception from thread B in thread A.
Is it possible to implement this and if so, how

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Oleg, 2018-02-14
@fortoster83

SELECT
  u.id, 
  u.name,
  u.email
FROM tbl_user u 
LEFT JOIN tbl_user_group ug 
  ON u.id = ug.user_id
WHERE 
  ug.group_id = 2

S
Sergey Gornostaev, 2019-08-27
@dadasay

There is no way to do this in the language, but you can use a hack that uses the CPython C API:

import ctypes
import threading
import time


def raise_async(thread, exception):
    if thread.ident is None:
        raise ValueError('Поток не запущен')
    r = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, ctypes.py_object(exception))
    if r == 0:
        raise ValueError('Неправильный идентификатор потока')
    elif r > 1:
        ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, 0)
        raise SystemError('Неожиданное состояние среды выполнения')


def f():
    print('Поток запущен')
    try:
        while True:
            time.sleep(1)
    except ZeroDivisionError:
        print('Эй! Я же ничего не делил!')


if __name__ == '__main__':
    t = threading.Thread(target=f)
    t.start()

    time.sleep(3)
    raise_async(t, ZeroDivisionError)

    t.join()

The truth is not the fact that it will help. If a thread is blocked on I/O, then the virtual machine will simply not do the exception checking.
And I repeat that your problem can certainly be solved in some other, more correct way.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question