Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of thread.interrupt_main() in Python 3

In Python 2 there is a function thread.interrupt_main(), which raises a KeyboardInterrupt exception in the main thread when called from a subthread.

This is also available through _thread.interrupt_main() in Python 3, but it's a low-level "support module", mostly for use within other standard modules.

What is the modern way of doing this in Python 3, presumably through the threading module, if there is one?

like image 367
isarandi Avatar asked Oct 30 '18 12:10

isarandi


People also ask

How do I run a thread in Python 3?

Creating Thread Using Threading ModuleDefine a new subclass of the Thread class. Override the __init__(self [,args]) method to add additional arguments. Then, override the run(self [,args]) method to implement what the thread should do when started.

Does Python 3 support multithreading?

Python doesn't support multi-threading because Python on the Cpython interpreter does not support true multi-core execution via multithreading.

How do you stop a thread in Python 3?

In order to kill a thread, we use hidden function _stop() this function is not documented but might disappear in the next version of python.

How do you extend a thread in Python?

Thread class can be extended to run code in another thread. This can be achieved by first extending the class, just like any other Python class. Then the run() function of the threading. Thread class must be overridden to contain the code that you wish to execute in another thread.


1 Answers

Well raising an exception manually is kinda low-level, so if you think you have to do that just use _thread.interrupt_main() since that's the equivalent you asked for (threading module itself doesn't provide this).

It could be that there is a more elegant way to achieve your ultimate goal, though. Maybe setting and checking a flag would be already enough or using a threading.Event like @RFmyD already suggested, or using message passing over a queue.Queue. It depends on your specific setup.

like image 158
Darkonaut Avatar answered Oct 19 '22 22:10

Darkonaut