examples: annotate examples
[nit.git] / lib / pthreads / redef_collections.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 # Redef _some_ basic collections to be thread-safe
18 #
19 # This modules is intended to be used with scripts or quick prototypes.
20 # It makes thread safe _all_ instances of _some_ collections which
21 # also slightly slow down single threaded use. For more robust software,
22 # it is recommended to use `threads::concurrent_collections`.
23 #
24 # Thread-safe collections:
25 #
26 # - [x] `Array`
27 # - [ ] `List`
28 # - [ ] `HashMap`
29 # - [ ] `HashSet`
30 # - [ ] `Ref`
31 # - [ ] `Queue`
32 module redef_collections
33
34 import pthreads
35
36 # Thread-safe refinements of most of the known methods (except `enlarge`)
37 redef class Array
38 var mutex = new Mutex
39
40 redef fun add(e)
41 do
42 mutex.lock
43 super
44 mutex.unlock
45 end
46
47 redef fun []=(index, e)
48 do
49 mutex.lock
50 super
51 mutex.unlock
52 end
53
54 redef fun [](index)
55 do
56 mutex.lock
57 var r = super
58 mutex.unlock
59 return r
60 end
61
62 redef fun remove_at(index)
63 do
64 mutex.lock
65 super
66 mutex.unlock
67 end
68
69 redef fun shift
70 do
71 mutex.lock
72 var r = super
73 mutex.unlock
74 return r
75 end
76
77 redef fun unshift(e)
78 do
79 mutex.lock
80 super
81 mutex.unlock
82 end
83
84 redef fun insert_all(from, pos)
85 do
86 mutex.lock
87 super
88 mutex.unlock
89 end
90
91 redef fun swap_at(a, b)
92 do
93 mutex.lock
94 super
95 mutex.unlock
96 end
97
98 redef fun ==(o)
99 do
100 mutex.lock
101 var r = super
102 mutex.unlock
103 return r
104 end
105
106 redef fun enlarge(cap)
107 do
108 mutex.lock
109 super
110 mutex.unlock
111 end
112 end