Advertisement
homer512

Closeable queue

May 17th, 2014
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. #!/usr/bin/python2
  2.  
  3.  
  4. import collections
  5. import threading
  6.  
  7.  
  8. class Pipe(collections.Iterable, collections.Sized):
  9.     def __init__(self):
  10.         self.deque = collections.deque()
  11.         self.closed = False
  12.         self.condition = threading.Condition()
  13.  
  14.     def put(self, element):
  15.         with self.condition:
  16.             if self.closed:
  17.                 raise EOFError("Pipe closed")
  18.             self.deque.append(element)
  19.             self.condition.notify()
  20.  
  21.     def pop(self):
  22.         with self.condition:
  23.             while not (self.deque or self.closed):
  24.                 self.condition.wait()
  25.             try:
  26.                 return self.deque.popleft()
  27.             except IndexError:
  28.                 raise EOFError("Pipe closed")
  29.  
  30.     def close(self):
  31.         with self.condition:
  32.             self.closed = True
  33.             self.condition.notify_all()
  34.  
  35.     def __len__(self):
  36.         with self.condition:
  37.             return len(self.deque)
  38.  
  39.     def __iter__(self):
  40.         return PipeIter(self)
  41.  
  42.  
  43. class PipeIter(collections.Iterator):
  44.     def __init__(self, pipe):
  45.         self.pipe = pipe
  46.  
  47.     def __iter__(self):
  48.         return self
  49.  
  50.     def next(self):
  51.         try:
  52.             return self.pipe.pop()
  53.         except EOFError:
  54.             raise StopIteration()
  55.  
  56.  
  57. def main():
  58.     pipe = Pipe()
  59.     elements = ["Foo", "Bar"]
  60.     for element in elements:
  61.         pipe.put(element)
  62.     pipe.close()
  63.     popped = list(pipe)
  64.     assert popped == elements
  65.  
  66. if __name__ == '__main__':
  67.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement