chain.py 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/usr/bin/env python
  2. """Create a chain of coroutines and pass a value from one end to the other,
  3. where each coroutine will increment the value before passing it along.
  4. """
  5. import optparse
  6. import time
  7. import greenlet
  8. def link(next_greenlet):
  9. value = greenlet.getcurrent().parent.switch()
  10. next_greenlet.switch(value + 1)
  11. def chain(n):
  12. start_node = greenlet.getcurrent()
  13. for i in xrange(n):
  14. g = greenlet.greenlet(link)
  15. g.switch(start_node)
  16. start_node = g
  17. return start_node.switch(0)
  18. if __name__ == '__main__':
  19. p = optparse.OptionParser(
  20. usage='%prog [-n NUM_COROUTINES]', description=__doc__)
  21. p.add_option(
  22. '-n', type='int', dest='num_greenlets', default=100000,
  23. help='The number of greenlets in the chain.')
  24. options, args = p.parse_args()
  25. if len(args) != 0:
  26. p.error('unexpected arguments: %s' % ', '.join(args))
  27. start_time = time.clock()
  28. print 'Result:', chain(options.num_greenlets)
  29. print time.clock() - start_time, 'seconds'