1 # This file is part of NIT (http://www.nitlanguage.org).
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 # A basic usage example of the modules `pthreads` and `pthreads::cocurrent_collections`
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
23 import pthreads
::concurrent_collections
25 private class MyThread
28 # This `ConcurrentArray` has its own `Mutex`
29 var array
: ConcurrentArray[String]
31 # Use an explicit `Barrier`
38 # Print and add to Array 1000 times
39 for i
in 1000.times
do
40 var str
= "thread {id}: {i}"
44 # Wait at the `barrier`
53 # This `ConcurrentArray` has its own `Mutex`
54 var array
= new ConcurrentArray[String]
56 # Use an explicit `Barrier`
57 var barrier
= new Barrier(n_threads
)
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
)
67 # Wait for the threads to complete
68 for thread
in threads
do
69 print
"Thread {thread.join or else "null"} is done"
72 print
"{array.length} strings inserted"