750f9762689147586e295dcd5c263033eb66427e
[nit.git] / lib / pthreads / examples / concurrent_array_and_barrier.nit
1 # This file is part of NIT (http://www.nitlanguage.org).
2 #
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # A basic usage example of the modules `pthreads` and `pthreads::cocurrent_collections`
18 #
19 # 20 threads share an array and a barrier. They each insert 1000 strings into
20 # the array and wait at a barrier before finishing.
21 module concurrent_array_and_barrier
22
23 import pthreads::concurrent_collections
24
25 private class MyThread
26 super Thread
27
28 # This `ConcurrentArray` has its own `Mutex`
29 var array: ConcurrentArray[String]
30
31 # Use an explicit `Barrier`
32 var barrier: Barrier
33
34 var id: Int
35
36 redef fun main
37 do
38 # Print and add to Array 1000 times
39 for i in 1000.times do
40 var str = "thread {id}: {i}"
41 array.add str
42 end
43
44 # Wait at the `barrier`
45 barrier.wait
46
47 return id
48 end
49 end
50
51 var n_threads = 20
52
53 # This `ConcurrentArray` has its own `Mutex`
54 var array = new ConcurrentArray[String]
55
56 # Use an explicit `Barrier`
57 var barrier = new Barrier(n_threads)
58
59 # Create all our threads
60 var threads = new Array[Thread]
61 for t in n_threads.times do
62 var thread = new MyThread(array, barrier, t)
63 threads.add thread
64 thread.start
65 end
66
67 # Wait for the threads to complete
68 for thread in threads do
69 print "Thread {thread.join or else "null"} is done"
70 end
71
72 print "{array.length} strings inserted"