我正在尝试从python线程调用多处理函数,以避免全局解释器锁影响我的多处理功能。
逻辑如下:
python --- ongoing python processing...
\
-> py thread -> py multiprocessing call -> C-code (dll/ctypes)
这有意义吗? C代码是在单独的核心上运行,还是这太复杂了?
感谢。
编辑:感谢您的回复。我应该澄清,但我需要调用第二个线程,因为我必须首先创建一个python数组,然后将指针传递给C函数。所以我不能过早地调用多处理函数(并且主要的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))
我在这里缺少什么?是否有不同的方法可以将内部处理与内联多处理结合使用?
答案 0 :(得分:1)
只要您不想在继续之前等待该流程完成,您就不需要在创建流程后立即加入。
这是并发编程的原理。
重要的是,您最终会致电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