How can I use threading in Python?
Threading is a way to run multiple threads (smaller units of a program) concurrently, in the same process. Python's threading
module is built on top of the lower-level _thread
module, which is built on top of the even lower-level thread
module. The threading
module is generally more convenient to use than the other two, and it should be sufficient for most purposes. Here is a simple example of how to use the threading
module:
import threading
def worker():
print("Worker thread")
thread = threading.Thread(target=worker)
thread.start()
This will start a new thread and run the worker
function in the new thread. The start()
method will return immediately, while the new thread will continue running until it finishes.
You can also pass arguments to the thread's target function by using the args
keyword argument:
import threading
def worker(num):
print("Worker thread", num)
thread = threading.Thread(target=worker, args=(1,))
thread.start()
In this example, the worker
function will be called with the argument 1
.
It's also possible to create a subclass of the Thread
class and override the run
method to specify the code that should be run in the new thread. Here is an example:
import threading
class MyThread(threading.Thread):
def run(self):
print("My thread")
thread = MyThread()
thread.start()
You can read more about the threading
module in the Python documentation: https://docs.python.org/3/library/threading.html