您可以
functools.partial为此使用(如您所怀疑的):
from functools import partialdef target(lock, iterable_item): for item in iterable_item: # Do cool stuff if (... some condition here ...): lock.acquire() # Write to stdout or logfile, etc. lock.release()def main(): iterable = [1, 2, 3, 4, 5] pool = multiprocessing.Pool() l = multiprocessing.Lock() func = partial(target, l) pool.map(func, iterable) pool.close() pool.join()
例:
def f(a, b, c): print("{} {} {}".format(a, b, c))def main(): iterable = [1, 2, 3, 4, 5] pool = multiprocessing.Pool() a = "hi" b = "there" func = partial(f, a, b) pool.map(func, iterable) pool.close() pool.join()if __name__ == "__main__": main()输出:
hi there 1hi there 2hi there 3hi there 4hi there 5



