python多处理:共享bitarray(bitarray 0.8.1)

时间:2016-05-05 20:11:11

标签: python multiprocessing bitarray

我想在多处理(https://pypi.python.org/pypi/bitarray/0.8.1)创建的线程之间共享一个3 GB的比特阵列(https://docs.python.org/2/library/multiprocessing.html)。

我只想在不修改的情况下阅读bitarray。以下python 2.7代码真的可以吗?不知何故,似乎没有使用ctypes(docs.python.org/2/library/ctypes.html)。

import multiprocessing as mp
import bitarray
import time
def f(x):
    n = 0
    #print shared_arr[n:(10+n)] & shared_arr[n:(10+n)]
    print "worker %d started at time %s" % (x, str(time.time()-start_time))
    print "running %d. bit %d of shared array is: " % (x, x) +str(shared_arr[n:(10+n)])
    time.sleep(2)
    print "ending %d at time %s" %(x, str(time.time()-start_time))
    return x*x

def main():
    print "The number of cpu is %d" % (mp.cpu_count())
    num_cpu_core = mp.cpu_count()
    n = 0
    global shared_arr
    global start_time
    start_time = time.time()
    shared_arr = bitarray.bitarray(18)
    shared_arr[:] = 0
    shared_arr[(n+5):(n+7)] = 1
    a = 10
    pool = mp.Pool(processes = num_cpu_core) # not saving one for the master process
    pool.map_async(f, range(10))
    pool.close()
    pool.join()

main()

2 个答案:

答案 0 :(得分:1)

这适用于使用fork multiprocessing语义的POSIX系统,但不适用于使用spawn语义的Windows系统。 fork语义将相同的内存映射到父和子(写时复制,因此如果它在一个中更改,则数据在另一个中保持不变); spawn语义启动了新的Python进程。

另外,请注意,在Windows上,我认为你需要一个导入防护来避免使用"叉炸弹"像方案一样,不要无条件地在模块级别调用main,但要用以下方式保护它:

if __name__ == '__main__':
    main()

因此,当衍生的孩子将主模块导入为#34;而不是主要"时,它不会尝试重新调用您的main函数。

答案 1 :(得分:-1)

您的脚本无法导入。

替换最后一行:

main()

有以下两行:

if __name__ == "__main__":
    main()