File: chain.py

package info (click to toggle)
python-greenlet 0.3.1-2.5
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 392 kB
  • sloc: ansic: 1,506; python: 666; makefile: 14
file content (38 lines) | stat: -rwxr-xr-x 1,058 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/env python

"""Create a chain of coroutines and pass a value from one end to the other,
where each coroutine will increment the value before passing it along.
"""

import optparse
import time

import greenlet

def link(next_greenlet):
    value = greenlet.getcurrent().parent.switch()
    while True:
        next_greenlet.switch(value + 1)

def chain(n):
    start_node = greenlet.getcurrent()
    for i in xrange(n):
        g = greenlet.greenlet(link)
        g.switch(start_node)
        start_node = g
    return start_node.switch(0)

if __name__ == '__main__':
    p = optparse.OptionParser(
        usage='%prog [-n NUM_COROUTINES]', description=__doc__)
    p.add_option(
        '-n', type='int', dest='num_greenlets', default=100000,
        help='The number of greenlets in the chain.')
    options, args = p.parse_args()

    if len(args) != 0:
        p.error('unexpected arguments: %s' % ', '.join(args))

    start_time = time.clock()
    print 'Result:', chain(options.num_greenlets)
    print time.clock() - start_time, 'seconds'