Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用多处理(多核或多线程)计算我的函数_Python_Multithreading - Fatal编程技术网

Python 使用多处理(多核或多线程)计算我的函数

Python 使用多处理(多核或多线程)计算我的函数,python,multithreading,Python,Multithreading,我使用下面的代码使用多个CPU核来计算一个函数(它是一个图像处理函数)。但是,当该过程完成时,返回的值是一个对象。我希望看到NumPy阵列。如有任何建议,我们将不胜感激 import datetime from multiprocessing import Process, current_process import sys ... def my_function(ImgDir, MaskDir, False, True): ... All_numpy_arrays = np

我使用下面的代码使用多个CPU核来计算一个函数(它是一个图像处理函数)。但是,当该过程完成时,返回的值是一个
对象
。我希望看到NumPy阵列。如有任何建议,我们将不胜感激

import datetime
from multiprocessing import Process, current_process
import sys
...

def my_function(ImgDir, MaskDir, False, True):
    ...
    All_numpy_arrays = np.dstack(foregrounds)
    return All_numpy_arrays

if __name__ == '__main__':
    worker_count = 6
    worker_pool = []
    p = None
    for _ in range(worker_count):
        result = Process(target=my_function,
                    args=(ImgDir, MaskDir, False, True))
        result.start()
        worker_pool.append(result)
    for result in worker_pool:
        result.join()  

    # Here I have another script that requires the *result* be a NumPy array

如果有帮助的话,我可以使用
ubuntu20.04
python3.8
您可以使用
多处理。Queue
如下:

import multiprocessing

def runme(i, q):
    q.put(i)

if __name__ == '__main__':
    multiprocessing.freeze_support() # windows support
    queue = multiprocessing.Queue()
    ps = [multiprocessing.Process(target=runme, args=[i, queue]) for i in range(6)]
    [p.start() for p in ps]
    [p.join() for p in ps]
    while True:
        try:
            print(queue.get_nowait())
        except multiprocessing.queues.Empty:
            break
上述输出类似于:

1
0
2
3
5
4

您可以像这样使用
多处理.Queue

import multiprocessing

def runme(i, q):
    q.put(i)

if __name__ == '__main__':
    multiprocessing.freeze_support() # windows support
    queue = multiprocessing.Queue()
    ps = [multiprocessing.Process(target=runme, args=[i, queue]) for i in range(6)]
    [p.start() for p in ps]
    [p.join() for p in ps]
    while True:
        try:
            print(queue.get_nowait())
        except multiprocessing.queues.Empty:
            break
上述输出类似于:

1
0
2
3
5
4

不能直接从进程返回数据。为此,您需要某种共享变量。查看一些方法,例如管理器或队列。您不使用(第一个示例)中演示的
map()
的任何原因?您不能直接从流程返回数据。为此,您需要某种共享变量。查看一些方法,例如管理器或队列。您不使用(第一个示例)中演示的
map()
的原因是什么?