Python多进程 在进程间共享数据,python进程,由于GIL的原因,Pyt


由于GIL的原因,Python不支持真正意义上的多线程

于是转而求其次,Python使用多进程来完成并行任务。

Python的multiprocessing库就是多进程的利器,能够简单快捷的进行多任务开发。

多进程间共享数据,可以使用 multiprocessing.Value 和 multiprocessing.Array

Value 和 Array:

Value(typecode_or_type, *args[, lock])

Value函数返回一个shared memory包装类,其中包含一个ctypes对象

参数:

@typecode_or_type typecode列表如下:

http://docs.python.org/library/array.html

Type code   C Type      Python Type'c'     char            character'b'         signed char         int'B'         unsigned char       int'u'         Py_UNICODE      Unicode character'h'         signed short        int'H'         unsigned short      int'i'         signed int      int'I'         unsigned int        long'l'         signed long         int'L'         unsigned long       long'f'         float       float'd'         double      float

一般 整数用 i, 字符用 c,浮点数用 d 就可以了

字符串需要用 Array 来传递

@args shared memory 中包含的值@lock 默认值是True:创建一个新的lock来控制对value的访问。该参数也可以是 multiprocessing.Lock 或 multiprocessing.RLock 对像,用来控制对value的访问

Array(typecode_or_type, size_or_initializer, *, lock=True)

Array函数返回一个shared memory包装类,其中包含一个数组

@typecode_or_type@size_or_initializer 大小或是初始值。初始值可以是 list,字符串等,也可以是多个变量@lock 同上
def worker(num, mystr, arr):    num.value *= 2    mystr.value = str(os.getpid())    for i in range(len(arr)):        arr[i] = arr[i] * -1 + 1.5def dump_vars(num, mystr, arr):    print 'num: ', num.value    print 'str: ', mystr[:]    print 'arr: ', arr[:]def test_sharedmemory():    num = Value('i', 5)    mystr = Array('c', 'just for test')    arr = Array('d', [1.0, 1.5, -2.0])    print 'init value'    dump_vars(num, mystr, arr)    ps = [Process(target=worker, args=(num, mystr, arr)) for _ in range(3)]    for p in ps:        p.start()    for p in ps:        p.join()    print    print 'after all workers finished'    dump_vars(num, mystr, arr)if __name__=='__main__':    test_sharedmemory()

转载自: http://u50.cn/blog/python%E5%9C%A8%E8%BF%9B%E7%A8%8B%E9%97%B4%E5%85%B1%E4%BA%AB%E6%95%B0%E6%8D%AE

评论关闭