Python 多线程执行方法有以下几种方式:\n\n1. 使用threading模块创建多线程:可以通过继承threading.Thread类或者直接使用threading.Thread(target=func)的方式创建线程对象,然后调用start()方法启动线程。\n\npython\nimport threading\n\nclass MyThread(threading.Thread):\n def run(self):\n # 线程执行的代码\n\nthread1 = MyThread()\nthread2 = threading.Thread(target=func)\nthread1.start()\nthread2.start()\n\n\n2. 使用concurrent.futures模块的线程池:可以使用ThreadPoolExecutor类来创建线程池,然后使用submit()方法提交任务给线程池执行。\n\npython\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef func():\n # 任务代码\n\nwith ThreadPoolExecutor() as executor:\n future1 = executor.submit(func)\n future2 = executor.submit(func)\n\n\n3. 使用multiprocessing模块的Pool类:可以使用Pool类创建进程池,然后使用apply_async()方法提交任务给进程池执行。\n\npython\nfrom multiprocessing import Pool\n\ndef func():\n # 任务代码\n\nwith Pool() as pool:\n result1 = pool.apply_async(func)\n result2 = pool.apply_async(func)\n result1.get()\n result2.get()\n\n\n需要注意的是,多线程的执行是并发执行的,而不是并行执行的。如果需要并行执行任务,可以使用multiprocessing模块创建多进程。


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

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