首页 > 解决方案 > 如何在 Python 中的 concurrent.futures.ProcessPoolExecutor 中传递“锁”?

问题描述

我正在真正的 Android 智能手机上使用 Python 3.7 和 Appium 1.15.1 运行并行测试。

我使用concurrent.futures.ProcessPoolExecutor在每个智能手机上运行每个测试。

我正在将智能手机的 uid 列表传递给我的地图功能。通过这种方式,我的方法“run_smartphone()”(启动测试)获取智能手机的 uid 并确定它必须在哪个智能手机上运行测试。

我的脚本工作正常,没有任何问题。但我想添加一个“锁”,因为 'run_smartphone()' 在 sqlite3 数据库上进行一些 I/O。如果我错了,请纠正我,但是在这个 sqlite3 数据库上“锁定”I/O 操作是一个好习惯吗?

这是我的原始代码,它有效:

def run_smartphone(p_udid):
    #do the stuff

list_smartphones_connected = [41492968379078, 53519716736397]
with concurrent.futures.ProcessPoolExecutor() as executor:
    try:
        multiprocesses = executor.map(mymodules.run_smartphone, list_smartphones_connected)

    except ValueError:
        print(("Error multiprocesses"))

所以我尝试将传递“锁定”添加到我的方法“run_smartphone()”中。这是我写的:

m = multiprocessing.Manager()
lock = m.Lock()
list_arguments_smartphones = []

list_smartphones_connected = [41492968379078, 53519716736397]
for smartphone_connected in list_smartphones_connected:        
    list_arguments_smartphones.append([smartphone_connected, lock])

with concurrent.futures.ProcessPoolExecutor() as executor:
    try:
        multiprocesses = executor.map(mymodules.run_smartphone, list_arguments_smartphones)

    except ValueError:
        print(("Error multiprocesses"))

但它不起作用,我没有提出任何异常。Pycharm 停止脚本:

Process finished with exit code 0

我不知道是什么停止了脚本。

因此,我开始通过使用以下行执行 1 部智能手机的脚本来进行调查:

 multiprocesses = executor.map(mymodules.run_smartphone, [41492968379078,lock])

它给出了相同的结果 => 脚本停止,没有自动启动,我没有看到任何异常引发(进程以退出代码 0 完成)。

因为我想知道问题到底出在哪里,所以我使用“trace”运行脚本。

py -m trace --trace  myscript.py

但我什么都不懂,我没有看到任何错误......你可以在我上传到 GitHub 上的文本文件中看到这个“跟踪”命令的输出:

https://github.com/gauthierbuttez/public/blob/master/trace-log.txt

有谁知道如何将“锁”传递给我的 concurrent.futures.ProcessPoolExecutor() ?这样做是个好主意吗?

谢谢。

标签: pythonpython-3.xmultiprocessinglockingpython-multiprocessing

解决方案


愿这能帮助你...

    m = multiprocessing.Manager()
    lock = m.Lock()

    def run_smartphone(p_udid, lock): 
        # further code

    list_smartphones_connected = [41492968379078, 53519716736397] 
    with concurrent.futures.ProcessPoolExecutor() as executor: 
        try: 
            multiprocesses = executor.map(run_smartphone, list_smartphones_connected, [lock]*len(list_smartphones_connected)) 
            for function_return_value in multiprocesses:
                print(function_return_value)

        except ValueError: 
            print(("Error multiprocesses"))

推荐阅读