在Python多进程编程中,实现资源共享需要使用multiprocessing
模块中的Value
、Array
和Manager
等类。这些类允许你在多个进程之间共享数据。下面是一些示例:
- 使用
Value
实现共享整数:
import multiprocessing def worker(shared_value): shared_value.value += 1 if __name__ == "__main__": shared_value = https://www.yisu.com/ask/multiprocessing.Value("i", 0) processes = [multiprocessing.Process(target=worker, args=(shared_value,)) for _ in range(10)] for process in processes: process.start() for process in processes: process.join() print("Shared value:", shared_value.value)
- 使用
Array
实现共享列表:
import multiprocessing def worker(shared_array): for i in range(len(shared_array)): shared_array[i] += 1 if __name__ == "__main__": shared_array = multiprocessing.Array("i", [0] * 10) processes = [multiprocessing.Process(target=worker, args=(shared_array,)) for _ in range(10)] for process in processes: process.start() for process in processes: process.join() print("Shared array:", shared_array[:])
- 使用
Manager
实现共享复杂数据结构:
import multiprocessing def worker(shared_dict): shared_dict["key"] += 1 if __name__ == "__main__": shared_dict = multiprocessing.Manager().dict({"key": 0}) processes = [multiprocessing.Process(target=worker, args=(shared_dict,)) for _ in range(10)] for process in processes: process.start() for process in processes: process.join() print("Shared dictionary:", shared_dict)
注意:在使用multiprocessing
模块时,需要确保代码在if __name__ == "__main__":
条件下运行,以避免在Windows操作系统上出现递归创建子进程的问题。