Python从独立线程调用多处理

2024-04-20 03:51:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从python线程调用一个多处理函数,以避免全局解释器锁影响我的多处理函数。你知道吗

逻辑如下:

python --- ongoing python processing...
       \
        -> py thread -> py multiprocessing call ->  C-code (dll/ctypes)

这有道理吗?C代码是在一个单独的内核上运行,还是太复杂而无法工作?你知道吗

谢谢。你知道吗

编辑:谢谢你的回复。我应该澄清一下,但是我需要调用第二个线程,因为我必须首先生成python数组,然后将指针传递给C函数。因此,我不能过早地调用multiprocessing函数(而且主要的python处理需要无缝地启动和继续)。你知道吗

编辑:下面是代码逻辑,以及为什么我不能调用与主代码内联的第二个进程:

main():
...
p = Process(target=save_c, args=(...,))
p.start()
p.join()   #Main thread will lock here and wait until return;

#Other code that needs to be processed follows the multiprocess call

save_c():
''' Function which calls C-module '''
_sum = ctypes.CDLL('/home/pi/murphylab_picam/temp/libsum.so')
_sum.c_function.argtypes = (ctypes.c_int, ctypes.POINTER(ctypes.c_int))
_sum.c_function(ctypes.c_int(num_numbers), array_type(*_sum.numbers))

我错过了什么?有没有一种不同的方式来将多处理与正在进行的处理结合使用?你知道吗


Tags: 函数代码py编辑savecode逻辑call
1条回答
网友
1楼 · 发布于 2024-04-20 03:51:42

您不需要在创建流程后立即加入,只要您不想等待该流程完成后再继续。你知道吗

这就是并发编程的原理。你知道吗

重要的是,您最终要调用join,否则您的主进程将终止,留下孤儿。你知道吗

child_process = Process(....)
child_process.start()  # the child process will start its independend execution here

do_some_stuff()
do_some_more_stuff()

child_process.join()  # here you are waiting for it to finish

相关问题 更多 >