Created
August 16, 2012 21:25
-
-
Save swinton/3373776 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| From: http://sdiehl.github.com/gevent-tutorial/#queues | |
| In this example we have the boss running simultaneously to the workers and have a restriction on the Queue that it can contain no more than three elements. This restriction means that the put operation will block until there is space on the queue. Conversely the get operation will block if there are no elements on the queue to fetch, it also takes a timeout argument to allow for the queue to exit with the exception gevent.queue.Empty if no work can found within the time frame of the Timeout. | |
| """ | |
| import gevent | |
| from gevent.queue import Queue, Empty | |
| tasks = Queue(maxsize=3) | |
| def worker(n): | |
| try: | |
| while True: | |
| task = tasks.get(timeout=1) # decrements queue size by 1 | |
| print('Worker %s got task %s' % (n, task)) | |
| gevent.sleep(0) | |
| except Empty: | |
| print('Quitting time!') | |
| def boss(): | |
| """ | |
| Boss will wait to hand out work until a individual worker is | |
| free since the maxsize of the task queue is 3. | |
| """ | |
| for i in xrange(1,10): | |
| tasks.put(i) | |
| print('Assigned all work in iteration 1') | |
| for i in xrange(10,20): | |
| tasks.put(i) | |
| print('Assigned all work in iteration 2') | |
| gevent.joinall([ | |
| gevent.spawn(boss), | |
| gevent.spawn(worker, 'steve'), | |
| gevent.spawn(worker, 'john'), | |
| gevent.spawn(worker, 'bob'), | |
| ]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment