1. 使用threading模块:Python的threading模块提供了创建和管理线程的方法。你可以创建一个线程对象,然后调用它的start()方法来启动线程。 ```python import threading def worker(num): """thread worker function""" print('Worker: %s' % num) threads = [] for i in range(5): t = threading.Thread(target=worker, args=(i,)) threads.append(t) t.start() ``` 2. 使用concurrent.futures模块:concurrent.futures模块提供了高级接口来执行可调用对象,包括线程池和进程池。 ```python import concurrent.futures def worker(num): """thread worker function""" print('Worker: %s' % num) with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: for i in range(5): future = executor.submit(worker, i) print('submitted %s' % future) ``` 3. 使用multiprocessing模块:multiprocessing模块提供了在多个处理器上并行运行任务的功能。 ```python import multiprocessing def worker(num): """thread worker function""" print('Worker: %s' % num) if __name__ == '__main__': with multiprocessing.Pool(processes=5) as pool: for i in range(5): pool.apply_async(worker, args=(i,)) ``` 4. 使用asyncio模块:asyncio模块提供了异步I/O操作的工具,可以用于编写高效的并发代码。 ```python import asyncio async def worker(num): """thread worker function""" print('Worker: %s' % num) async def main(): tasks = [worker(i) for i in range(5)] await asyncio.gather(*tasks) if __name__ == '__main__': asyncio.run(main()) ``` 注意:在多线程编程中,需要注意线程安全问题,例如竞态条件、死锁等。 [2023-11-07 22:03:40 | AI调研报告 | 412点数解答]