【问题标题】:python multiprocessing: sharing bitarray (bitarray 0.8.1)python多处理:共享bitarray(bitarray 0.8.1)
【发布时间】:2016-08-31 18:16:13
【问题描述】:

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

我只想读取位数组而不修改它。下面的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()

【问题讨论】:

  • 多处理不会创建线程,它会创建进程

标签: python multiprocessing bitarray


【解决方案1】:

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

另外,旁注,在 Windows 上,我认为您需要一个导入保护来避免类似“分叉炸弹”的情况,不要在模块级别无条件调用 main,而是使用以下方法保护它:

if __name__ == '__main__':
    main()

因此,当生成的子模块将主模块导入为“非主模块”时,它不会尝试重新调用您的 main 函数。

【讨论】:

    【解决方案2】:

    您的脚本不可导入。

    替换最后一行:

    main()
    

    以下两行:

    if __name__ == "__main__":
        main()
    

    【讨论】:

    • 这不是答案。
    猜你喜欢
    • 2015-11-11
    • 2012-04-24
    • 2011-09-10
    • 2016-10-29
    • 2016-02-21
    • 2015-10-02
    • 2012-09-03
    • 2018-08-30
    相关资源
    最近更新 更多