3d12f6f5f81fbcbbabbd33d3a03bbaaed5d754ca
[nit.git] / lib / pthreads / examples / jointask_example.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 # Simple example of joinable task using threadpool
16 module jointask_example
17
18 import threadpool
19
20 # Task computing a string
21 class StringTask
22 super JoinTask
23
24 # Sleeping time
25 var sec: Int
26
27 # result of `self` execution
28 var value: String
29
30 # ID for printing
31 var id: Int
32
33 redef fun main do
34 nanosleep(sec, 0)
35 value += " id: {id}"
36 end
37 end
38
39 var tp = new ThreadPool
40 var t0 = new StringTask(10, "First, long task", 0)
41 var tasks = new Array[StringTask]
42 for i in 5.times do
43 tasks.add(new StringTask(1, "Small task", i + 1))
44 end
45 tp.execute(t0)
46 for t in tasks do tp.execute(t)
47 for t in tasks do
48 t.join
49 print t.value
50 end
51 t0.join
52 print t0.value