多进程共享变量

import multiprocessing

# 不能将共享变量和共享锁定义成全局变量然后通过global引用那样会报错,只能传过来

def sub_process(process_name,share_var,share_lock):

    # 获取锁

    share_lock.acquire()

    share_var.append(process_name)

    # 释放锁

    share_lock.release()

    for item in share_var:

        print(f"{process_name}-{item}")

    pass

def main_process():

    # 单个值声明方式。typecode是进制类型,value是初始值

    # share_var = multiprocessing.Manager().Value(typecode, value)

    # 数组声明方式。typecode是数组变量中的变量类型,sequence是数组初始值

    # share_var = multiprocessing.Manager().Array(typecode, sequence)

    # 字典声明方式

    # share_var = multiprocessing.Manager().dict()

    # 列表声明方式

    share_var = multiprocessing.Manager().list()

    share_var.append("start flag")

    # 声明一个共享锁

    share_lock = multiprocessing.Manager().Lock()

    process_list = []

    process_name = "process 1"

    tmp_process = multiprocessing.Process(target=sub_process,args=(process_name,share_var,share_lock))

    process_list.append(tmp_process)

    process_name = "process 2"

    tmp_process = multiprocessing.Process(target=sub_process, args=(process_name,share_var,share_lock))

    process_list.append(tmp_process)

    for process in process_list:

        process.start()

    for process in process_list:

        process.join()

if __name__ == "__main__":

    main_process()

转载自:https://www.cnblogs.com/lsdb/p/10815319.html

你可能感兴趣的:(多进程共享变量)