thread ring example from benchmarksgame
[nit.git] / lib / actors / examples / thread-ring / thread_ring.nit
1 # This file is part of NIT (http://www.nitlanguage.org).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Example implemented from "The computer Language Benchmarks Game" - Thread-Ring
16 # http://benchmarksgame.alioth.debian.org/
17 #
18 # Complete description of the thread-ring :
19 # http://benchmarksgame.alioth.debian.org/u64q/threadring-description.html#threadring
20 module thread_ring
21
22 import actors
23
24 # One Actor, who will receive the token
25 class ThreadRing
26 actor
27
28 # Identification of `self`
29 var id: Int
30
31 # The next Actor to which `self` send the token
32 var next: ThreadRing is noinit
33
34 # Receive a token, then send it to `next` unless its value is `0`
35 fun send_token(message: Int) do
36 if message == 0 then
37 print id
38 end
39 if message >= 1 then
40 next.async.send_token(message - 1)
41 end
42 end
43 end
44
45 var first = new ThreadRing(1)
46 var current = new ThreadRing(2)
47 first.next = current
48 for i in [3..503] do
49 var t = new ThreadRing(i)
50 current.next = t
51 current = t
52 end
53 current.next = first
54 if args.is_empty then
55 first.send_token(1000)
56 else
57 first.send_token(args[0].to_i)
58 end