python - 如何在 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() ?这样做是个好主意吗?
谢谢。
解决方案
愿这能帮助你...
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"))
推荐阅读
- php - 如何使用 htaccess 和 php 避免错误变量
- c# - 图像 src 指向 WEB FORM 中我的项目文件夹之外的文件
- c# - 为什么在面向 .NET Standard 的项目中可以不分配 Out 参数?
- python - 在循环中动态命名保存的数据帧
- java - 设置/更改默认 Java MaxHeapSize 或更改默认 JVM 命令设置
- python - 使用python对数据进行均匀和奇数切片
- azure - 是否可以在 Azure DevOps 的 Azure Powershell 任务中设置变量并将它们传递给另一个任务?
- java - 如何使用视图和路径变量测试 Spring 控制器?
- typescript - Vite 在 main.ts 中使用别名导入 CSS
- c++ - macOS 10.15 Catalina 上的英特尔编译问题:灾难性错误:无法打开源文件“stdlib.h”