Multiprocessing Queue Batch Get Up To Max N Elements
I need to get as many items as I can from a queue (up to N), in a blocking fashion. e.g: queue.get(16) Should return up to 16 elements, but block if empty.
Solution 1:
There's no such facility built in, so you'll need to code it yourself; for example,
import queue # in Python 3; Queue in Python 2
...
defgetn(q, n):
result = [q.get()] # block until at least 1try: # add more until `q` is empty or `n` items obtainedwhilelen(result) < n:
result.append(q.get(block=False))
except queue.Empty:
passreturn result
Then do getn(queue, 16)
for your conceptual queue.get(16)
.
Solution 2:
It waits 3 sec, if queue is empty. It returns last not full batch.
defget_batch_from_queue(q, batch_size):
item_list = []
try:
for i inrange(batch_size):
item_list.append(q.get(block=True, timeout=3))
return item_list
except queue.Empty:
if(len(item_list)==0):
returnNoneelse:
return item_list
whileTrue:
batch = get_batch_from_queue(q, batch_size=8)
if batch == None:
breakprint('len(batch)', len(batch))
Post a Comment for "Multiprocessing Queue Batch Get Up To Max N Elements"