Python多线程执行方法有以下几种方式:

  1. 使用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()
  1. 使用concurrent.futures模块的线程池:可以使用ThreadPoolExecutor类来创建线程池,然后使用submit()方法提交任务给线程池执行。
from concurrent.futures import ThreadPoolExecutor

def func():
    # 任务代码

with ThreadPoolExecutor() as executor:
    future1 = executor.submit(func)
    future2 = executor.submit(func)
  1. 使用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模块创建多进程

Python多线程执行方法

原文地址: https://www.cveoy.top/t/topic/hWWL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录