在Python多進程編程中,實現資源共享需要使用multiprocessing
模塊中的Value
、Array
和Manager
等類。這些類允許你在多個進程之間共享數據。下面是一些示例:
Value
實現共享整數:import multiprocessing
def worker(shared_value):
shared_value.value += 1
if __name__ == "__main__":
shared_value = 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操作系統上出現遞歸創建子進程的問題。