File: coroutine.fal

package info (click to toggle)
falconpl 0.9.6.9-git20120606-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 46,176 kB
  • sloc: cpp: 181,389; ansic: 109,025; yacc: 2,310; xml: 1,218; sh: 403; objc: 245; makefile: 82; sql: 20
file content (104 lines) | stat: -rw-r--r-- 2,267 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
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
   Falcon Samples.

   Coroutine / light parallelism test

   This script creates eight coroutines from objects (actually
   from methods, as Falcon accepts only function calls as
   semantically correct coroutines), and one control coroutine
   that shows the status of the other coroutines.

   Both the main coroutine and the updater are notified of
   relevant events via two different semaphores.

   The script uses willfully a combination of global variables,
   parameter passing and object access to test and show the
   different approaches.

*/

//==================================================
// Global variables
ended = 0


//=================================================
// Updater thread
//

function updater( waiter, coroutineArray )
   while true
      // print the number of ended arrays
      print( "\rE:", ended )

      // print data on all the coroutines
      for elem in coroutineArray
         print( @"   c$(elem.id)=$(elem.value:3)" )
      end

      print( "\r" )
      //wait for new updates
      if ended < 8
         waiter.wait()
      else
         // a break would do too here.
         yieldOut()
      end
   end
end


//===============================================
// coroutine class
//
class coroutine( param, su, se )
   id = param
   sem_updates = su
   sem_ended = se
   value = 0

   // =======================
   // Thread method
   // (could have any name)
   function run( param )
      for i in [1 : 101]
         self.value = i
         sleep( 0.01 * self.id )
         self.sem_updates.post()
      end
      // access rw the global variable
      global ended
      ended ++
      // warn both listening threads
      self.sem_updates.post()
      self.sem_ended.post()
   end
end

//========================================================
// Main program

// our semaphores
end_semaphore = Semaphore()
upd_semaphore = Semaphore()

// we save the coroutine objects here
coro_array = []

for i in [0 : 8]
   coro = coroutine( i, upd_semaphore, end_semaphore )
   coro_array += coro

   launch coro.run( i )
end

// Functions can be started normally
launch updater( upd_semaphore, coro_array )

// wait for all the threads to end
while ended < 8
   end_semaphore.wait()
end

printl()
printl( "Done" )