~ubuntu-branches/ubuntu/karmic/pypy/karmic

« back to all changes in this revision

Viewing changes to demo/pickle_coroutine.py

  • Committer: Bazaar Package Importer
  • Author(s): Alexandre Fayolle
  • Date: 2007-04-13 09:33:09 UTC
  • Revision ID: james.westby@ubuntu.com-20070413093309-yoojh4jcoocu2krz
Tags: upstream-1.0.0
ImportĀ upstreamĀ versionĀ 1.0.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""
 
2
Stackless demo.
 
3
 
 
4
This example only works on top of a pypy-c compiled with stackless features
 
5
and the signal module:
 
6
 
 
7
    translate.py --stackless targetpypystandalone --withmod-signal
 
8
 
 
9
Usage:
 
10
 
 
11
    pypy-c pickle_coroutine.py --start demo.pickle
 
12
 
 
13
        Start the computation.  You can interrupt it at any time by
 
14
        pressing Ctrl-C; at this point, the state of the computing
 
15
        coroutine is saved in demo.pickle.
 
16
 
 
17
    pypy-c pickle_coroutine.py --resume demo.pickle
 
18
 
 
19
        Reload the coroutine from demo.pickle and continue running it.
 
20
        (It can be interrupted again with Ctrl-C.)
 
21
 
 
22
This demo is documented in detail in pypy/doc/stackless.txt.
 
23
"""
 
24
 
 
25
try:
 
26
    import sys, pickle, signal
 
27
    from stackless import coroutine
 
28
except ImportError:
 
29
    print __doc__
 
30
    sys.exit(2)
 
31
 
 
32
 
 
33
def ackermann(x, y):
 
34
    check()
 
35
    if x == 0:
 
36
        return y + 1
 
37
    if y == 0:
 
38
        return ackermann(x - 1, 1)
 
39
    return ackermann(x - 1, ackermann(x, y - 1))
 
40
 
 
41
# ____________________________________________________________
 
42
 
 
43
main = coroutine.getcurrent()
 
44
sys.setrecursionlimit(100000)
 
45
 
 
46
interrupt_flag = False
 
47
 
 
48
def interrupt_handler(*args):
 
49
    global interrupt_flag
 
50
    interrupt_flag = True
 
51
 
 
52
def check():
 
53
    if interrupt_flag:
 
54
        main.switch()
 
55
 
 
56
 
 
57
def execute(coro):
 
58
    signal.signal(signal.SIGINT, interrupt_handler)
 
59
    res = coro.switch()
 
60
    if res is None and coro.is_alive:    # interrupted!
 
61
        print "interrupted! writing %s..." % (filename,)
 
62
        f = open(filename, 'w')
 
63
        pickle.dump(coro, f)
 
64
        f.close()
 
65
        print "done"
 
66
    else:
 
67
        print "result:", res
 
68
 
 
69
try:
 
70
    operation, filename = sys.argv[1:]
 
71
except ValueError:
 
72
    print __doc__
 
73
    sys.exit(2)
 
74
 
 
75
if operation == '--start':
 
76
    coro = coroutine()
 
77
    coro.bind(ackermann, 3, 7)
 
78
    print "running from the start..."
 
79
    execute(coro)
 
80
elif operation == '--resume':
 
81
    print "reloading %s..." % (filename,)
 
82
    f = open(filename)
 
83
    coro = pickle.load(f)
 
84
    f.close()
 
85
    print "done, running now..."
 
86
    execute(coro)