good way to build a blocking, zero-length queue in python

  • Last Update :
  • Techknowledgy :

You can use Queue.join() and Queue.task_done() to block until the get() has completed:

class SynchronousQueue(object):

   def __init__(self):
   self.q = Queue(1)
self.put_lock = RLock()

def get(self):
   value = self.q.get(block = True)
self.q.task_done()
return value

def put(self, item):
   with self.put_lock:
   self.q.put(item, block = True)
self.q.join()

I have the feeling the following might be deadlock city, but would something like the following work?

class SynchronousQueue(object):
   def __init__(self):
   self.ready_to_get = Queue(1)
self.queue = Queue(1)

def get(self):
   self.ready_to_get.put('ready', block = True)
return self.queue.get(block = True)

def put(self, item):
   self.ready_to_get.get(block = True)
self.queue.put(item, block = True)

Suggestion : 2

Constructor for a LIFO queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue size is infinite.,Constructor for a FIFO queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue size is infinite.,Constructor for a priority queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue size is infinite.,Raises a ValueError if called more times than there were items placed in the queue.

from dataclasses
import dataclass, field
from typing
import Any

@dataclass(order = True)
class PrioritizedItem:
   priority: int
item: Any = field(compare = False)
import threading
import queue

q = queue.Queue()

def worker():
   while True:
   item = q.get()
print(f 'Working on {item}')
print(f 'Finished {item}')
q.task_done()

# Turn - on the worker thread.
threading.Thread(target = worker, daemon = True).start()

# Send thirty task requests to the worker.
for item in range(30):
   q.put(item)

# Block until all tasks are done.
q.join()
print('All work completed')

Suggestion : 3

Last Updated : 06 Jul, 2022

Output: 
 

Initial queue
   ['a', 'b', 'c']

Elements dequeued from queue
a
b
c

Queue after removing elements
   []

 

Traceback(most recent call last):
   File "/home/ef51acf025182ccd69d906e58f17b6de.py", line 25, in
print(queue.pop(0))
IndexError: pop from empty list