This question is similar to How to use multiprocessing in a for loop - python
and How to use multiprocessing in a for loop - python
, but neither of these solves my problem. The function stateRecognizer() checks if a series of images exists on current screen, using a function getCoord(imgDir), and returns the corresponding state.
getCoord(key) returns an list of 4 integers. getCoord(key) returns None if the image wasn't found.
My for loop implementation
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]
When I attempt to write another function and call it, it does not return the expected variable:
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)
Outputs:
stateChecker() missing 1 required positional argument: 'value'
How do I pass in a dict to the function stateChecker?
Update 2: Thank you both @tdelaney and @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())
The function now returns [None, None, None, None, 'bathtub', None, None, None, None, None, None] with slower processing speed (around 12 times slower).I am assuming each subprocess processes the entire dict per subprocess. Also, sometimes the function fails to read the JPEG image properly.
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
When with * before checks.items() or checks
with Pool(multiprocessing.cpu_count()) as mp_pool:
return mp_pool.starmap(stateChecker, *checks)
Exception raised:
Exception has occurred: TypeError
starmap() takes from 3 to 4 positional arguments but 13 were given
if __name__ == '__main__'like the error suggests?