source:
doc/papers/concurrency/examples/ProdCons.py
@
29075d1
Last change on this file since 29075d1 was a573c22, checked in by , 5 years ago | |
---|---|
|
|
File size: 871 bytes |
Rev | Line | |
---|---|---|
[1e5d0f0c] | 1 | def Prod( N ): |
[a573c22] | 2 | cons = yield # get cons |
3 | yield # resume scheduler | |
[1e5d0f0c] | 4 | for i in range( N ): |
5 | print( "prod" ) | |
[a573c22] | 6 | yield cons # execute next |
[1e5d0f0c] | 7 | print( "end", "prod" ) |
8 | ||
9 | def Cons( N ): | |
[a573c22] | 10 | prod = yield # get prod |
11 | yield # resume scheduler | |
[1e5d0f0c] | 12 | for i in range( N ): |
13 | print( "cons" ) | |
[a573c22] | 14 | yield prod # execute next |
[1e5d0f0c] | 15 | print( "end", "cons" ) |
16 | ||
17 | def Scheduler(): | |
[a573c22] | 18 | n = yield # starting coroutine |
19 | try: | |
20 | while True: | |
21 | n = next( n ) # schedule coroutine | |
22 | except StopIteration: | |
23 | pass | |
[1e5d0f0c] | 24 | |
25 | prod = Prod( 5 ) | |
26 | cons = Cons( 5 ) | |
[a573c22] | 27 | next( prod ) # prime |
28 | prod.send( cons ) # send cons | |
29 | next( cons ) # prime | |
30 | cons.send( prod ) # send prod | |
[1e5d0f0c] | 31 | |
32 | s = Scheduler(); | |
[a573c22] | 33 | next( s ) # prime |
[1e5d0f0c] | 34 | try: |
35 | s.send( prod ) # start cycle | |
[a573c22] | 36 | except StopIteration: # scheduler stopped |
37 | pass | |
[1e5d0f0c] | 38 | print( "stop" ) |
39 | ||
40 | # Local Variables: # | |
41 | # tab-width: 4 # | |
[a573c22] | 42 | # compile-command: "python3.7 ProdCons.py" # |
[1e5d0f0c] | 43 | # End: # |
Note: See TracBrowser
for help on using the repository browser.