温馨提示×

Python多进程编程怎样实现资源共享

小樊
81
2024-11-09 12:08:43
栏目: 编程语言

在Python多进程编程中,实现资源共享需要使用multiprocessing模块中的ValueArrayManager等类。这些类允许你在多个进程之间共享数据。下面是一些示例:

  1. 使用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)
  1. 使用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[:])
  1. 使用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操作系统上出现递归创建子进程的问题。

0