Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

Python - Multiprocessing StarMap with two arguments

I've a function that runs multiple queries in parallel but I'm having some troubles to run my function using multprocessing with more than argument. I've this code:

def run(args):
    query, cursor = args
    cursor.execute(query)
with multiprocessing.Pool(processes=10) as pool:
    args = (product(queries),cursor)
    results = pool.starmap(run(args))

If I run only pool.starmap(run(product(queries))) it works well, however I have the need to pass also the cursor object.

How I can do that?

I'm having the following error:

TypeError: starmap() missing 1 required positional argument: 'iterable'
question from:https://stackoverflow.com/questions/66069021/python-multiprocessing-starmap-with-two-arguments

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are some problems with your code:

  • you call run with parameters, then pass the result to starmap, but you have to pass both the function and its parameters separately to starmap
  • your args are a tuple of first the product of all queries, then the cursor, but you rather want to combine each of those query-combinations with the cursor
  • your function expects a single parameter that you then unpack inside the function, so you should use map; for starmap it should be def run(query, cursor)

Try this:

import multiprocessing
import itertools

def run(args):
    query, cursor = args
    print("running", query, cursor)

queries = ["foo", "bar", "blub"]
cursor = "whatever"
    
with multiprocessing.Pool(processes=10) as pool:
    args = ((args, cursor) for args in itertools.product(queries))
    results = pool.map(run, args)

There may be more "upstream" errors, like that SSLSocket stuff, but this should at least (try to) call the function with the correct parameters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...