Python多线程执行方法
Python多线程执行方法有以下几种方式:
- 使用
threading模块创建多线程:可以通过继承threading.Thread类或者直接使用threading.Thread(target=func)的方式创建线程对象,然后调用start()方法启动线程。
import threading
class MyThread(threading.Thread):
def run(self):
# 线程执行的代码
thread1 = MyThread()
thread2 = threading.Thread(target=func)
thread1.start()
thread2.start()
- 使用
concurrent.futures模块的线程池:可以使用ThreadPoolExecutor类来创建线程池,然后使用submit()方法提交任务给线程池执行。
from concurrent.futures import ThreadPoolExecutor
def func():
# 任务代码
with ThreadPoolExecutor() as executor:
future1 = executor.submit(func)
future2 = executor.submit(func)
- 使用
multiprocessing模块的Pool类:可以使用Pool类创建进程池,然后使用apply_async()方法提交任务给进程池执行。
from multiprocessing import Pool
def func():
# 任务代码
with Pool() as pool:
result1 = pool.apply_async(func)
result2 = pool.apply_async(func)
result1.get()
result2.get()
需要注意的是,多线程的执行是并发执行的,而不是并行执行的。如果需要并行执行任务,可以使用multiprocessing模块创建多进程
原文地址: https://www.cveoy.top/t/topic/hWWL 著作权归作者所有。请勿转载和采集!