1 """A multi-producer, multi-consumer queue."""
3 # define this exception to be compatible with Python 1.5's class
4 # exceptions, but also when -X option is used.
6 class Empty(Exception):
11 # string based exceptions
12 # exception raised by get(block=0)/get_nowait()
14 # exception raised by put(block=0)/put_nowait()
18 def __init__(self
, maxsize
=0):
19 """Initialize a queue object with a given maximum size.
21 If maxsize is <= 0, the queue size is infinite.
25 self
.mutex
= thread
.allocate_lock()
26 self
.esema
= thread
.allocate_lock()
28 self
.fsema
= thread
.allocate_lock()
31 """Return the approximate size of the queue (not reliable!)."""
38 """Return 1 if the queue is empty, 0 otherwise (not reliable!)."""
45 """Return 1 if the queue is full, 0 otherwise (not reliable!)."""
51 def put(self
, item
, block
=1):
52 """Put an item into the queue.
54 If optional arg 'block' is 1 (the default), block if
55 necessary until a free slot is available. Otherwise (block
56 is 0), put an item on the queue if a free slot is immediately
57 available, else raise the Full exception.
61 elif not self
.fsema
.acquire(0):
64 was_empty
= self
._empty
()
72 def put_nowait(self
, item
):
73 """Put an item into the queue without blocking.
75 Only enqueue the item if a free slot is immediately available.
76 Otherwise raise the Full exception.
78 return self
.put(item
, 0)
80 def get(self
, block
=1):
81 """Remove and return an item from the queue.
83 If optional arg 'block' is 1 (the default), block if
84 necessary until an item is available. Otherwise (block is 0),
85 return an item if one is immediately available, else raise the
90 elif not self
.esema
.acquire(0):
93 was_full
= self
._full
()
102 def get_nowait(self
):
103 """Remove and return an item from the queue without blocking.
105 Only get an item if one is immediately available. Otherwise
106 raise the Empty exception.
110 # Override these methods to implement other queue organizations
111 # (e.g. stack or priority queue).
112 # These will only be called with appropriate locks held
114 # Initialize the queue representation
115 def _init(self
, maxsize
):
116 self
.maxsize
= maxsize
120 return len(self
.queue
)
122 # Check wheter the queue is empty
124 return not self
.queue
126 # Check whether the queue is full
128 return self
.maxsize
> 0 and len(self
.queue
) == self
.maxsize
130 # Put a new item in the queue
131 def _put(self
, item
):
132 self
.queue
.append(item
)
134 # Get an item from the queue