Home | History | Annotate | Download | only in threads
      1 # Coroutine example:  controlling multiple instances of a single function
      2 
      3 from Coroutine import *
      4 
      5 # fringe visits a nested list in inorder, and detaches for each non-list
      6 # element; raises EarlyExit after the list is exhausted
      7 def fringe(co, list):
      8     for x in list:
      9         if type(x) is type([]):
     10             fringe(co, x)
     11         else:
     12             co.back(x)
     13 
     14 def printinorder(list):
     15     co = Coroutine()
     16     f = co.create(fringe, co, list)
     17     try:
     18         while 1:
     19             print co.tran(f),
     20     except EarlyExit:
     21         pass
     22     print
     23 
     24 printinorder([1,2,3])  # 1 2 3
     25 printinorder([[[[1,[2]]],3]]) # ditto
     26 x = [0, 1, [2, [3]], [4,5], [[[6]]] ]
     27 printinorder(x) # 0 1 2 3 4 5 6
     28 
     29 # fcmp lexicographically compares the fringes of two nested lists
     30 def fcmp(l1, l2):
     31     co1 = Coroutine(); f1 = co1.create(fringe, co1, l1)
     32     co2 = Coroutine(); f2 = co2.create(fringe, co2, l2)
     33     while 1:
     34         try:
     35             v1 = co1.tran(f1)
     36         except EarlyExit:
     37             try:
     38                 v2 = co2.tran(f2)
     39             except EarlyExit:
     40                 return 0
     41             co2.kill()
     42             return -1
     43         try:
     44             v2 = co2.tran(f2)
     45         except EarlyExit:
     46             co1.kill()
     47             return 1
     48         if v1 != v2:
     49             co1.kill(); co2.kill()
     50             return cmp(v1,v2)
     51 
     52 print fcmp(range(7), x)  #  0; fringes are equal
     53 print fcmp(range(6), x)  # -1; 1st list ends early
     54 print fcmp(x, range(6))  #  1; 2nd list ends early
     55 print fcmp(range(8), x)  #  1; 2nd list ends early
     56 print fcmp(x, range(8))  # -1; 1st list ends early
     57 print fcmp([1,[[2],8]],
     58            [[[1],2],8])  #  0
     59 print fcmp([1,[[3],8]],
     60            [[[1],2],8])  #  1
     61 print fcmp([1,[[2],8]],
     62            [[[1],2],9])  # -1
     63 
     64 # end of example
     65