首页 > 解决方案 > 返回多处理 shared_memory 数组时内核重新启动

问题描述

我有以下代码,其中我使用多处理方法来更改共享内存中数组的值(使用多处理 shared_memory)。

我注意到当我尝试从 main() 函数返回共享内存中的数组时,内核重新启动。如果我返回其他内容(例如 0),代码将正常运行。

from multiprocessing import shared_memory
import numpy as np
import concurrent 
from functools import partial

def main():
    
    def add(shared_matrix,index_to_change):
        shared_matrix[index_to_change-1] += 1

    input_list = [1,2,3,4]

    shared_matrix_base = np.array([1.5,2.5,3.5,4.5])
    sharedMemory_matrix = shared_memory.SharedMemory(create=True,size=shared_matrix_base.nbytes)
    shared_matrix = np.ndarray(shared_matrix_base.shape, dtype=shared_matrix_base.dtype, buffer=sharedMemory_matrix.buf)
    shared_matrix[:] = shared_matrix_base[:] # copy values
    
    print('Shared_matrix',shared_matrix)
    
    add_other_partial = partial(add,shared_matrix)
    
    with concurrent.futures.ThreadPoolExecutor() as executor:
        executor.map(add_other_partial,input_list)

    print('Shared Matrix',shared_matrix)

    # return 0 # no problem
    return shared_matrix    
    
output = main()

知道为什么会发生此内核重启吗?我在 macOS Big Sur 中使用 Spyder 4 和 Python 3.8。

标签: pythonmultiprocessingshared-memoryrestart

解决方案


推荐阅读