多处理池中的Matlab引擎版本R2022b卡住,有什么建议吗?

pbgvytdp  于 7个月前  发布在  Matlab
关注(0)|答案(1)|浏览(130)

我开发了Python代码,版本3.8.5,通过它调用R2018a Matlab使用matlab引擎函数,使用ubuntu 20.04处理数据。我使用了多处理库中的pool命令,在使用Matlab引擎加速处理的同时,我能够使用20个线程。代码运行良好,我能够多次获得结果。然而,我已经将Matlab升级到R2022b版本,现在使用完全相同的代码,我们面临着在池内调用MATLAB引擎的问题。代码在到达Matlab引擎函数时卡住,甚至没有打开Matlab函数来处理数据。它被卡在“启动Matlab引擎”,无法继续。我使用的是jueyter notebook,但是,我在终端中使用.py尝试了我的代码,仍然得到了相同的结果。我创建了一个示例代码,如下所示,供您审阅。请注意,Matlab引擎在单独调用时工作得很好。此外,池在单独调用时也能按预期工作。但是,当在池中调用Matlab引擎时,代码会卡住。我很感激任何意见或反馈,以帮助我解决这个问题。

import multiprocessing
from multiprocessing import Pool
import matlab.engine
import time

    
print("defining function ...")

    
def function88 (j):
    print("cal result1 ... ")
    result1=j**2
    print(result1)

    print("Starting Matlab engine...")
    eng = matlab.engine.start_matlab()
    print("Matlab engine started...")

    print("Calling Matlab function...")
    out = eng.test(j)
                    
                    
    print("Matlab function output:")
    print(out)

    return result1

print("calling pool ...")
pool = multiprocessing.Pool(1)

print("calling pool.map")
time.sleep(3)
result = pool.map(function88, range(10))

print("printing result")
print (result)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The result is as follows:

defining function ...
calling pool ...
calling pool.map
cal result1 ... 
0
Starting Matlab engine...

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

My expectation was to see the Matlab function output.
pgvzfuti

pgvzfuti1#

如果这个问题仍然相关的话。我也有类似的问题,对我来说,它有助于在多进程函数调用中启动和结束matlab引擎。
每个进程调用多个matlab执行的伪代码看起来像这样:

def run_matlab_in_parallel(batch_data):
    res_list = []
    ## Start Matlab Engine
    eng = matlab.engine.start_matlab(background=False)  
    eng.cd(r'''Directory of Matlab Script''')
    
    ## Run Script 
    for params in enumerate(batch_data):
        a, b, c = params
        res = eng.my_matlab_script(a, b, c, background=True).result()
        res_list.append(res)
    
    ## End Engine
    eng.quit()
    return res_list

def main():
    ## Start Pool with n_cpu = 2
    with Pool(2) as p:
        matlab_matrix = p.starmap(run_matlab_in_parallel, multi_process_params)
    
    ## Convert Matlab Mat into Numpy Array
    matlab_arr = np.array(matlab_matrix)
    return matlab_arr

相关问题