from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(16)
res = pool.map(one_arg_fun, [arg1, arg2, ...])
A 3 line IO parallelism speedup trick. Used it fetch stuff from multiple servers recently. from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(16)
res = pool.map(one_arg_fun, [arg1, arg2, ...])
A 3 line IO parallelism speedup trick. Used it fetch stuff from multiple servers recently.Python3 has asyncio as part of the stdlib but for Python2 there are a variety of coroutine libraries out there (I think the most widely recognized being gevent).
> I believe multiprocessing.dummy is just a wrapper for threading which has context switching overhead [1].
Yap. But I am fetching and waiting for data to come from servers half-way across the country. Not worried about too much thread switching overhead. The point it was still faster than a for loop with a fetch. It was replaced by 3 lines which was 10x faster.
Python releases GIL during IO so that's why thread-based pool works for IO parallelism and there is no need to fork. Was that what you mentioned? Sorry, I don't think I completely followed.
from threading import Thread
def blocking_function(arg):
....
pool = []
for arg in args[:16]:
f = lambda: blocking_function(arg)
thread = Thread(target=f)
thread.start()
pool.append(thread)
Edit: see below, this doesn't include job queueing but rather, hard limits your input to maximum 16 args. The point is, the code is a nice, easy way to start a number of threads working on a list of arguments.It doesn't have true CPU parallelism like multiple processes would have, but it works for IO code.
It's a little gold nuggest in the multiprocessing lib.