溫馨提示×

Python多進(jìn)程編程怎樣實(shí)現(xiàn)資源共享

小樊
81
2024-11-09 12:08:43
欄目: 編程語言

在Python多進(jìn)程編程中,實(shí)現(xiàn)資源共享需要使用multiprocessing模塊中的Value、ArrayManager等類。這些類允許你在多個(gè)進(jìn)程之間共享數(shù)據(jù)。下面是一些示例:

  1. 使用Value實(shí)現(xiàn)共享整數(shù):
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實(shí)現(xiàn)共享列表:
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實(shí)現(xiàn)共享復(fù)雜數(shù)據(jù)結(jié)構(gòu):
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模塊時(shí),需要確保代碼在if __name__ == "__main__":條件下運(yùn)行,以避免在Windows操作系統(tǒng)上出現(xiàn)遞歸創(chuàng)建子進(jìn)程的問題。

0