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):
60 was_empty
= self
._empty
()
62 # If we fail before here, the empty state has
63 # not changed, so we can skip the release of esema
66 # If we fail before here, the queue can not be full, so
67 # release_full_sema remains True
68 release_fsema
= not self
._full
()
70 # Catching system level exceptions here (RecursionDepth,
71 # OutOfMemory, etc) - so do as little as possible in terms
77 def put_nowait(self
, item
):
78 """Put an item into the queue without blocking.
80 Only enqueue the item if a free slot is immediately available.
81 Otherwise raise the Full exception.
83 return self
.put(item
, 0)
85 def get(self
, block
=1):
86 """Remove and return an item from the queue.
88 If optional arg 'block' is 1 (the default), block if
89 necessary until an item is available. Otherwise (block is 0),
90 return an item if one is immediately available, else raise the
95 elif not self
.esema
.acquire(0):
100 was_full
= self
._full
()
102 # If we fail before here, the full state has
103 # not changed, so we can skip the release of fsema
106 # Failure means empty state also unchanged - release_esema
108 release_esema
= not self
._empty
()
115 def get_nowait(self
):
116 """Remove and return an item from the queue without blocking.
118 Only get an item if one is immediately available. Otherwise
119 raise the Empty exception.
123 # Override these methods to implement other queue organizations
124 # (e.g. stack or priority queue).
125 # These will only be called with appropriate locks held
127 # Initialize the queue representation
128 def _init(self
, maxsize
):
129 self
.maxsize
= maxsize
133 return len(self
.queue
)
135 # Check whether the queue is empty
137 return not self
.queue
139 # Check whether the queue is full
141 return self
.maxsize
> 0 and len(self
.queue
) == self
.maxsize
143 # Put a new item in the queue
144 def _put(self
, item
):
145 self
.queue
.append(item
)
147 # Get an item from the queue
149 return self
.queue
.pop(0)