pythonまとめ(二一)マルチプロセスデータ共有と同期_サービスプロセスマネージャ


# -*- coding: utf-8 -*-
"""
               multiprocessing.Manager
    

  :
    20          

  :
    1. Mangeer   Value,Array
    2.        ,       
    3.             ,         

    :
    1.                
        list1 = manager.list([1,2,3,4,5])
        dict1 = manager.dict()
        array1 = manager.Array('i',range(10))
        value1 = manager.Value('i',1)
    2.            
        lock = manager.Lock()
        RLock
        Semaphore
        Condition
    3.          

  :
method: ['Array', 'BoundedSemaphore', 'Condition', 'Event', 'JoinableQueue'
, 'Lock', 'Namespace', 'Pool', 'Queue', 'RLock', 'Semaphore', 'Value', '_Client'
,'_finalize_manager', '_number_of_objects', '_run_server',
'connect', 'dict', 'get_server', 'join', 'list', 'register', 'start']

"""

from multiprocessing import Process,Manager
import time

def func1(shareList, shareValue, shareDict, lock):
    """
                 
    """

    # lock with   
    # with lock:
    #     for i in xrange(len(shareList)):
    #         shareList[i] += 1
    #
    #     shareValue.value += 1
    #
    #     shareDict[1] = '1'
    #     shareDict[2] = '2'
    #
    #     time.sleep(1)


    lock.acquire() #    

    ##       
    for i in xrange(len(shareList)):
        shareList[i] += 1

    shareValue.value += 1

    shareDict[1] = '1'
    shareDict[2] = '2'

    time.sleep(0.1)

    lock.release()  #    


if __name__ == '__main__':
    #   Manager  
    manager = Manager()

    #             
    list1 = manager.list([1,2,3,4,5])
    dict1 = manager.dict()
    array1 = manager.Array('i',range(10))
    value1 = manager.Value('i',1)

    print "before"
    print list1
    print dict1
    print array1
    print value1

    lock = manager.Lock() #    

    #   20     ,     
    proc = [ Process(target=func1, args=(list1,value1,dict1,lock)) for i in xrange(20) ]

    #        
    for p in proc:    #                 
        p.start()

    #          
    for p in proc:
        p.join()

    print "after"
    print list1
    print dict1
    print array1
    print value1

"""
Out:

before
[1, 2, 3, 4, 5]
{}
array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Value('i', 1)
after
[21, 22, 23, 24, 25]
{1: '1', 2: '2'}
array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Value('i', 21)

"""

 
転載先:https://www.cnblogs.com/sunzebo/p/9635507.html