1 """A multi-producer, multi-consumer queue."""
3 class Empty(Exception):
4 "Exception raised by Queue.get(block=0)/get_nowait()."
8 "Exception raised by Queue.put(block=0)/put_nowait()."
12 def __init__(self
, maxsize
=0):
13 """Initialize a queue object with a given maximum size.
15 If maxsize is <= 0, the queue size is infinite.
19 self
.mutex
= thread
.allocate_lock()
20 self
.esema
= thread
.allocate_lock()
22 self
.fsema
= thread
.allocate_lock()
25 """Return the approximate size of the queue (not reliable!)."""
32 """Return 1 if the queue is empty, 0 otherwise (not reliable!)."""
39 """Return 1 if the queue is full, 0 otherwise (not reliable!)."""
45 def put(self
, item
, block
=1):
46 """Put an item into the queue.
48 If optional arg 'block' is 1 (the default), block if
49 necessary until a free slot is available. Otherwise (block
50 is 0), put an item on the queue if a free slot is immediately
51 available, else raise the Full exception.
55 elif not self
.fsema
.acquire(0):
58 was_empty
= self
._empty
()
66 def put_nowait(self
, item
):
67 """Put an item into the queue without blocking.
69 Only enqueue the item if a free slot is immediately available.
70 Otherwise raise the Full exception.
72 return self
.put(item
, 0)
74 def get(self
, block
=1):
75 """Remove and return an item from the queue.
77 If optional arg 'block' is 1 (the default), block if
78 necessary until an item is available. Otherwise (block is 0),
79 return an item if one is immediately available, else raise the
84 elif not self
.esema
.acquire(0):
87 was_full
= self
._full
()
97 """Remove and return an item from the queue without blocking.
99 Only get an item if one is immediately available. Otherwise
100 raise the Empty exception.
104 # Override these methods to implement other queue organizations
105 # (e.g. stack or priority queue).
106 # These will only be called with appropriate locks held
108 # Initialize the queue representation
109 def _init(self
, maxsize
):
110 self
.maxsize
= maxsize
114 return len(self
.queue
)
116 # Check whether the queue is empty
118 return not self
.queue
120 # Check whether the queue is full
122 return self
.maxsize
> 0 and len(self
.queue
) == self
.maxsize
124 # Put a new item in the queue
125 def _put(self
, item
):
126 self
.queue
.append(item
)
128 # Get an item from the queue