python singleton into multiprocessing

前端 未结 5 739
时光取名叫无心
时光取名叫无心 2021-01-13 02:53

How can I code to share the same instance of a \"singletonic\" class among processes?

5条回答
  •  南方客
    南方客 (楼主)
    2021-01-13 03:41

    You could also use one of the multiprocessing.manager shareable data types

    import multiprocessing as mp
    manager = mp.Manager()
    shared_list = manager.list()
    
    def worker1(l):
        l.append(1)
    
    def worker2(l):
        l.append(2)
    
    process1 = mp.Process(target=worker1, args=[shared_list])
    process2 = mp.Process(target=worker2, args=[shared_list])
    
    process1.start()
    process2.start()
    process1.join()
    process2.join()
    
    print shared_list
    

    output would look like:

    [1, 2]

    There are a variety of data structures on offer but you'll need the parent process to pass in the shared object to the child objects.

提交回复
热议问题