Python多线程编程:深入理解threading模块及代码实战【第99篇—Multiprocessing模块】_python multithreading模块
import multiprocessing
def worker(num):
"""
A simple worker function that prints numbers.
:param num: The number to print.
"""
print(f"Worker: {num}")
if __name__ == "__main__":
# Create a list of numbers to send to multiple processes
numbers = [1, 2, 3, 4, 5]
# Create a list of processes
processes = [multiprocessing.Process(target=worker, args=(num,)) for num in numbers]
# Start all the processes
for process in processes:
process.start()
# Wait for all processes to finish
for process in processes:
process.join()
print("All processes have finished execution.")
这段代码使用Python的multiprocessing
模块创建了多个进程,每个进程运行worker
函数,并将不同的数字作为参数传入。代码首先定义了worker
函数,然后在主程序中,创建了一个进程列表,并启动所有进程。最后,主程序等待所有进程完成工作后再继续执行。这是一个多进程编程的简单示例。
评论已关闭