Merge: Sys is top
[nit.git] / lib / pthreads / pthreads.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 # Main POSIX threads support and intro the classes `Thread`, `Mutex` and `Barrier`
18 module pthreads is
19 cflags "-pthread"
20 ldflags "-pthread"
21 pkgconfig "bdw-gc"
22 new_annotation threaded
23 end
24
25 #
26 ## Native part
27 #
28 # Nity part at the bottom of the module.
29 #
30
31 in "C Header" `{
32 #include <pthread.h>
33 `}
34
35 in "C" `{
36 // TODO protect with: #ifdef WITH_LIBGC
37 // We might have to add the next line to gc_chooser.c too, especially
38 // if we get an error like "thread not registered with GC".
39 #ifndef ANDROID
40 #define GC_THREADS
41 #include <gc.h>
42 #endif
43 `}
44
45 redef class Sys
46
47 # `NativePthread` for running thread
48 private fun native_pthread_self: NativePthread `{
49 pthread_t *id = malloc(sizeof(pthread_t));
50 *id = pthread_self();
51 return id;
52 `}
53
54 private var self_thread_key = new NativePthreadKey
55
56 private var main_thread_cache: nullable MainThread = null
57 private var main_thread_mutex = new Mutex
58
59 # Handle to the program's main thread
60 fun main_thread: MainThread
61 do
62 var cache = main_thread_cache
63 if cache != null then return cache
64
65 main_thread_mutex.lock
66
67 # Recheck if cache has been updated since lock has been unlocked/locked
68 cache = main_thread_cache
69 if cache != null then
70 main_thread_mutex.unlock
71 return cache
72 end
73
74 # Create a `MainThread` exactly once
75 var thread = new MainThread
76 thread.native = sys.native_pthread_self
77 main_thread_cache = thread
78
79 main_thread_mutex.unlock
80 return thread
81 end
82 end
83
84 private extern class NativePthread in "C" `{ pthread_t * `}
85
86 new create(nit_thread: Thread) import Thread.main_intern `{
87 pthread_attr_t attr;
88 pthread_attr_init(&attr);
89
90 pthread_t thread;
91 int r = pthread_create(&thread, &attr, (void * (*)(void *))&Thread_main_intern, nit_thread);
92
93 if (r == 0) {
94 pthread_t *pthread = malloc(sizeof(pthread_t));
95 memmove(pthread, &thread, sizeof(pthread_t));
96 return pthread;
97 }
98 return NULL;
99 `}
100
101 new create_ex(nit_thread: Thread, attr: NativePthreadAttr) import Thread.main_intern `{
102 pthread_t thread;
103 int r = pthread_create(&thread, attr, (void * (*)(void *))&Thread_main_intern, nit_thread);
104
105 if (r == 0) {
106 pthread_t *pthread = malloc(sizeof(pthread_t));
107 memmove(pthread, &thread, sizeof(pthread_t));
108 return pthread;
109 }
110 return NULL;
111 `}
112
113 fun join: nullable Object `{
114 void *thread_return;
115 pthread_join(*recv, &thread_return);
116 if(thread_return == NULL) thread_return = null_Object();
117 return (nullable_Object)thread_return;
118 `}
119
120 fun equal(other: NativePthread): Bool `{ return pthread_equal(*recv, *other); `}
121
122 fun kill(signal: Int) `{ pthread_kill(*recv, signal); `}
123 end
124
125 private extern class NativePthreadAttr in "C" `{ pthread_attr_t * `}
126 new `{
127 pthread_attr_t attr;
128 int r = pthread_attr_init(&attr);
129 if (r == 0) {
130 pthread_attr_t *pattr = malloc(sizeof(pthread_attr_t));
131 memmove(pattr, &attr, sizeof(pthread_attr_t));
132 return pattr;
133 }
134 return NULL;
135 `}
136
137 fun destroy `{
138 pthread_attr_destroy(recv);
139 `}
140
141 # Most features of this class are still TODO
142 #
143 # * pthread_attr_setaffinity_np(3)
144 # * pthread_attr_setdetachstate
145 # * pthread_attr_setguardsize
146 # * pthread_attr_setinheritsched
147 # * pthread_attr_setschedparam
148 # * pthread_attr_setschedpolicy
149 # * pthread_attr_setscope
150 # * pthread_attr_setstack
151 # * pthread_attr_setstackaddr
152 # * pthread_attr_setstacksize
153 end
154
155 private extern class NativePthreadMutex in "C" `{ pthread_mutex_t * `}
156 new (attr: NativePthreadMutexAttr) `{
157 pthread_mutex_t *mutex = malloc(sizeof(pthread_mutex_t));
158 int res = pthread_mutex_init(mutex, attr);
159 return mutex;
160 `}
161
162 fun destroy `{ pthread_mutex_destroy(recv); `}
163
164 fun lock `{ pthread_mutex_lock(recv); `}
165 fun try_lock: Bool `{ return pthread_mutex_trylock(recv); `}
166 fun unlock `{ pthread_mutex_unlock(recv); `}
167 end
168
169 private extern class NativePthreadMutexAttr in "C" `{ pthread_mutexattr_t * `}
170 new `{
171 pthread_mutexattr_t *attr = malloc(sizeof(pthread_mutexattr_t));
172 int res = pthread_mutexattr_init(attr);
173 return attr;
174 `}
175
176 fun destroy `{ pthread_mutexattr_destroy(recv); `}
177
178 fun set_type_normal `{ pthread_mutexattr_settype(recv, PTHREAD_MUTEX_NORMAL); `}
179 fun set_type_recursive `{ pthread_mutexattr_settype(recv, PTHREAD_MUTEX_RECURSIVE); `}
180 fun set_type_errorcheck `{ pthread_mutexattr_settype(recv, PTHREAD_MUTEX_ERRORCHECK); `}
181
182 # pthread_mutexattr_setpshared
183 # pthread_mutexattr_setprotocol
184 # pthread_mutexattr_setproceiling
185 # pthread_mutexattr_setrobust_np
186 end
187
188 private extern class NativePthreadKey in "C" `{ pthread_key_t * `}
189 new `{
190 pthread_key_t *key = malloc(sizeof(pthread_key_t));
191 int res = pthread_key_create(key, NULL);
192 return key;
193 `}
194
195 fun get: nullable Object `{
196 void *val = pthread_getspecific(*recv);
197 if (val == NULL) val = null_Object();
198 return val;
199 `}
200
201 fun set(val: nullable Object) `{
202 pthread_setspecific(*recv, val);
203 `}
204 end
205
206 private extern class NativePthreadCond in "C" `{ pthread_cond_t * `}
207 new `{
208 pthread_cond_t cond;
209 int r = pthread_cond_init(&cond, NULL);
210 if (r == 0) {
211 pthread_cond_t *pcond = malloc(sizeof(pthread_cond_t));
212 memmove(pcond, &cond, sizeof(pthread_cond_t));
213 return pcond;
214 }
215 return NULL;
216 `}
217
218 fun destroy `{ pthread_cond_destroy(recv); `}
219
220 fun signal `{ pthread_cond_signal(recv); `}
221
222 fun broadcast `{ pthread_cond_broadcast(recv); `}
223
224 fun wait(mutex: NativePthreadMutex) `{ pthread_cond_wait(recv, mutex); `}
225 end
226
227 #
228 ## Nity part
229 #
230 # Cannot be extracted from this module because of the callback from C to `Thread::run`
231 #
232
233 # Handle to a thread
234 #
235 # Instances of this class are each used to launch and control a thread.
236 abstract class Thread
237 super Finalizable
238
239 private var native: nullable NativePthread = null
240
241 # Main method of this thread
242 #
243 # The returned valued is passed to the caller of `join`.
244 fun main: nullable Object do return null
245
246 private fun main_intern: nullable Object
247 do
248 # Register thread local data
249 sys.self_thread_key.set self
250
251 return main
252 end
253
254 # Start executing this thread
255 #
256 # Will launch `main` on a different thread.
257 fun start
258 do
259 if native != null then return
260 native = new NativePthread.create(self)
261 end
262
263 # Join this thread to the calling thread
264 #
265 # Blocks until the method `main` returns or the target thread calls
266 # `Sys::thread_exit`. Returns the object returned from the other thread.
267 #
268 # Stats the thread if now already done by a call to `start`.
269 fun join: nullable Object
270 do
271 if native == null then start
272 var r = native.join
273 native = null
274 return r
275 end
276
277 redef fun finalize
278 do
279 if native == null then return
280 native.free
281 native = null
282 end
283 end
284
285 # The main thread of the program
286 class MainThread
287 super Thread
288
289 private init do end
290 end
291
292 # Exit current thread and return `value` to caller of `Thread::join`
293 fun exit_thread(value: nullable Object) `{ pthread_exit(value); `}
294
295 # Returns the handle to the running `Thread`
296 fun thread: Thread
297 do
298 var key = sys.self_thread_key
299 var val = key.get
300 if val == null then
301 # This is the original thread, get `Sys::main_thread` and store it
302 var thread = sys.main_thread
303 key.set thread
304 return thread
305 end
306
307 assert val isa Thread
308 return val
309 end
310
311 # Mutual exclusion synchronization tool
312 #
313 # Instances of this class can only be acquired by a single thread at any one
314 # point in time. Uses the recursive protocol so they can be locked many time by
315 # the same thread, must then be unlocked as many time.
316 class Mutex
317 super Finalizable
318
319 private var native: nullable NativePthreadMutex is noinit
320
321 init
322 do
323 var attr = new NativePthreadMutexAttr
324 attr.set_type_recursive
325 native = new NativePthreadMutex(attr)
326 attr.destroy
327 attr.free
328 end
329
330 # Acquire this lock, wait until it is available
331 fun lock do native.lock
332
333 # Acquire this lock only if it is available
334 #
335 # Returns `true` if the lock has been acquired.
336 fun try_lock: Bool do return native.try_lock
337
338 # Release this lock, unblocking all callers of `lock`
339 fun unlock do native.unlock
340
341 redef fun finalize
342 do
343 var native = self.native
344 if native != null then
345 native.destroy
346 native.free
347 end
348 self.native = null
349 end
350 end
351
352 # Barrier synchronization tool
353 #
354 # Ensures that `count` threads call and block on `wait` before releasing them.
355 class Barrier
356 super Finalizable
357
358 private var mutex = new Mutex
359 private var cond: nullable NativePthreadCond = new NativePthreadCond
360
361 # Number of threads that must be waiting for `wait` to unblock
362 var count: Int
363
364 private var threads_waiting = 0
365
366 # Wait at this barrier and block until there are a `count` threads waiting
367 fun wait
368 do
369 mutex.lock
370 threads_waiting += 1
371 if threads_waiting == count then
372 threads_waiting = 0
373 cond.broadcast
374 else
375 cond.wait(mutex.native.as(not null))
376 end
377 mutex.unlock
378 end
379
380 redef fun finalize
381 do
382 var cond = self.cond
383 if cond != null then
384 cond.destroy
385 cond.free
386 end
387 self.cond = null
388 end
389 end
390
391 # Print `object` and '\n' with the same system call
392 redef fun print(object)
393 do
394 sys.stdout.write(object.to_s+"\n")
395 end