I liked the ability to turn a function into a thread without the unnecessary line to define a class. I know about _thread, however it appears that you are not supposed to use _thread. Is there a good-practice equivalent of thread.start_new_thread for python 3?
Python doesn't support multi-threading because Python on the Cpython interpreter does not support true multi-core execution via multithreading.
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.
Python is NOT a single-threaded language. Python processes typically use a single thread because of the GIL. Despite the GIL, libraries that perform computationally heavy tasks like numpy, scipy and pytorch utilise C-based implementations under the hood, allowing the use of multiple cores.
You need to assign the thread object to a variable and then start it using that varaible: thread1=threading. Thread(target=f) followed by thread1. start() . Then you can do thread1.
threading.Thread(target=some_callable_function).start()
or if you wish to pass arguments,
threading.Thread(target=some_callable_function, args=(tuple, of, args), kwargs={'dict': 'of', 'keyword': 'args'}, ).start()
Unfortunately there is not a direct equivalent, because Python 3 is meant to be more portable than Python 2 and the _thread
interface is seen as too low-level for this purpose.
In Python 3 the best practice is usually to use threading.Thread(target=f...)
. This uses different semantics, but is preferred because the interface is easier to port to other Python implementations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With