forked from thepian/pypy
/
pickle_coroutine.py
86 lines (66 loc) · 1.98 KB
/
pickle_coroutine.py
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"""
Stackless demo.
This example only works on top of a pypy-c compiled with stackless features
and the signal module:
translate.py --stackless targetpypystandalone --withmod-signal
Usage:
pypy-c pickle_coroutine.py --start demo.pickle
Start the computation. You can interrupt it at any time by
pressing Ctrl-C; at this point, the state of the computing
coroutine is saved in demo.pickle.
pypy-c pickle_coroutine.py --resume demo.pickle
Reload the coroutine from demo.pickle and continue running it.
(It can be interrupted again with Ctrl-C.)
This demo is documented in detail in pypy/doc/stackless.txt.
"""
try:
import sys, pickle, signal
from stackless import coroutine
except ImportError:
print __doc__
sys.exit(2)
def ackermann(x, y):
check()
if x == 0:
return y + 1
if y == 0:
return ackermann(x - 1, 1)
return ackermann(x - 1, ackermann(x, y - 1))
# ____________________________________________________________
main = coroutine.getcurrent()
sys.setrecursionlimit(100000)
interrupt_flag = False
def interrupt_handler(*args):
global interrupt_flag
interrupt_flag = True
def check():
if interrupt_flag:
main.switch()
def execute(coro):
signal.signal(signal.SIGINT, interrupt_handler)
res = coro.switch()
if res is None and coro.is_alive: # interrupted!
print "interrupted! writing %s..." % (filename,)
f = open(filename, 'w')
pickle.dump(coro, f)
f.close()
print "done"
else:
print "result:", res
try:
operation, filename = sys.argv[1:]
except ValueError:
print __doc__
sys.exit(2)
if operation == '--start':
coro = coroutine()
coro.bind(ackermann, 3, 7)
print "running from the start..."
execute(coro)
elif operation == '--resume':
print "reloading %s..." % (filename,)
f = open(filename)
coro = pickle.load(f)
f.close()
print "done, running now..."
execute(coro)