【发布时间】:2021-09-17 11:39:56
【问题描述】:
这个问题类似于How to use multiprocessing in a for loop - python
和How to use multiprocessing in a for loop - python
,但这些都不能解决我的问题。函数stateRecognizer()使用函数getCoord(imgDir)检查当前屏幕上是否存在一系列图像,并返回相应的状态。
getCoord(key) 返回一个包含 4 个整数的列表。 getCoord(key) 如果未找到图像,则返回 None。
我的for循环实现
checks = {"loadingblack.png": 'loading',
"loading.png": 'loading',
"gear.png": 'home',
"factory.png": 'factory',
"bathtub.png": 'bathtub',
"refit.png": 'refit',
"supply.png": 'supply',
"dock.png": 'dock',
"spepage.png": 'spepage',
"oquest.png": 'quest',
"quest.png": 'quest'}
def stateRecognizer(hint=None):
for key in checks:
if (getCoord(key) is not None):
return checks[key]
当我尝试编写另一个函数并调用它时,它没有返回预期的变量:
def stateChecker(key, value):
if (getCoord(key) is not None):
return value
def stateRecognizer():
with Pool(multiprocessing.cpu_count()) as pool:
result = pool.map(stateChecker, checks)
输出:
stateChecker() missing 1 required positional argument: 'value'
如何将dict 传递给函数stateChecker?
更新 2: 谢谢@tdelaney 和@Nathaniel Ford。
def stateChecker(key, value):
if (getCoord(key) is not None):
return value
def stateRecognizer():
with Pool(multiprocessing.cpu_count()) as mp_pool:
return mp_pool.starmap(stateChecker, checks.items())
该函数现在返回 [None, None, None, None, 'bathtub', None, None, None, None, None, None] 处理速度较慢(大约慢 12 倍)。我假设每个子进程处理每个子进程的整个字典。此外,有时该函数无法正确读取 JPEG 图像。
Premature end of JPEG file
Premature end of JPEG file
[None, None, None, None, None, None, None, None, None, None, None]
Elapsed time: 7.7098618000000005
Premature end of JPEG file
Premature end of JPEG file
[None, None, None, None, 'bathtub', None, None, None, None, None, None]
Elapsed time: 7.169349200000001
当* 在checks.items() 或checks 之前使用时
with Pool(multiprocessing.cpu_count()) as mp_pool:
return mp_pool.starmap(stateChecker, *checks)
引发异常:
Exception has occurred: TypeError
starmap() takes from 3 to 4 positional arguments but 13 were given
【问题讨论】:
-
您是否像错误提示的那样使用
if __name__ == '__main__'保护主模块? -
感谢您解决了第 2 部分 @flakes
-
您可能应该解决您遇到的第二个问题,进入它自己的问题。有几件事可能正在发生,但你应该隔离。此外,根据您的具体操作,您可能会遇到 GIL 问题。
-
感谢您指出 GIL 的概念。
标签: python multiprocessing threadpool pool