This article mainly introduces four ways to start threads in Python.
1. Using the threading module
Create a Thread object and then call the start() method to start the thread.
import threading
def func():
print("Hello, World!")
t = threading.Thread(target=func)
t.start()
2. Inherit threading.Thread class
Override the run() method and call the start() method to start the thread.
import threading
class MyThread(threading.Thread):
def run(self):
print("Hello, World!")
t = MyThread()
t.start()
3. Using the concurrent.futures module
Use the submit() method of the ThreadPoolExecutor class to submit a task, automatically create a thread pool and execute the task.
import concurrent.futures
def func():
print("Hello, World!")
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(func)
4. Use the Process class of the multiprocessing module
Create a process, and start a thread within the process.
import multiprocessing
import threading
def func():
print("Hello, World!")
if __name__ == "__main__":
p = multiprocessing.Process(target=func)
p.start()
p.join()
The above is an introduction to several ways to start threads in python. I hope it will be helpful to you.