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 # Main POSIX threads support and intro the classes `Thread`, `Mutex` and `Barrier`
19 c_compiler_option
("-pthread")
20 c_linker_option
("-pthread")
26 # Nity part at the bottom of the module.
34 // TODO protect with: #ifdef WITH_LIBGC
35 // We might have to add the next line to gc_chooser.c too, especially
36 // if we get an error like "thread not registered with GC".
45 # `NativePthread` for running thread
46 private fun native_pthread_self
: NativePthread `{
47 pthread_t *id = malloc(sizeof(pthread_t));
52 private var self_thread_key
= new NativePthreadKey
54 private var main_thread_cache
: nullable MainThread = null
55 private var main_thread_mutex
= new Mutex
57 # Handle to the program's main thread
58 fun main_thread
: MainThread
60 var cache
= main_thread_cache
61 if cache
!= null then return cache
63 main_thread_mutex
.lock
65 # Recheck if cache has been updated since lock has been unlocked/locked
66 cache
= main_thread_cache
68 main_thread_mutex
.unlock
72 # Create a `MainThread` exactly once
73 var thread
= new MainThread
74 thread
.native
= sys
.native_pthread_self
75 main_thread_cache
= thread
77 main_thread_mutex
.unlock
82 private extern class NativePthread in "C" `{ pthread_t * `}
84 new create(nit_thread: Thread) import Thread.main_intern `{
86 pthread_attr_init
(&attr
);
89 int r
= pthread_create
(&thread
, &attr
, (void
* (*)(void
*))&Thread_main_intern, nit_thread
);
92 pthread_t
*pthread
= malloc
(sizeof
(pthread_t
));
93 memmove
(pthread
, &thread
, sizeof
(pthread_t
));
99 new create_ex(nit_thread: Thread, attr: NativePthreadAttr) import Thread.main_intern `{
101 int r
= pthread_create
(&thread
, attr
, (void
* (*)(void
*))&Thread_main_intern, nit_thread
);
104 pthread_t
*pthread
= malloc
(sizeof
(pthread_t
));
105 memmove
(pthread
, &thread
, sizeof
(pthread_t
));
111 fun join: nullable Object `{
113 pthread_join
(*recv
, &thread_return
);
114 if(thread_return
== NULL) thread_return
= null_Object
();
115 return (nullable_Object
)thread_return
;
118 fun attr: NativePthreadAttr `{
119 pthread_attr_t
*pattr
= malloc
(sizeof
(pthread_attr_t
));
120 pthread_getattr_np
(*recv
, pattr
);
124 fun equal(other: NativePthread): Bool `{ pthread_equal(*recv, *other); `}
126 fun kill
(signal
: Int) `{ pthread_kill(*recv, signal); `}
129 private extern class NativePthreadAttr in "C" `{ pthread_attr_t * `}
132 int r = pthread_attr_init(&attr);
134 pthread_attr_t *pattr = malloc(sizeof(pthread_attr_t));
135 memmove(pattr, &attr, sizeof(pthread_attr_t));
142 pthread_attr_destroy(recv);
145 # Most features of this class are still TODO
147 # * pthread_attr_setaffinity_np(3)
148 # * pthread_attr_setdetachstate
149 # * pthread_attr_setguardsize
150 # * pthread_attr_setinheritsched
151 # * pthread_attr_setschedparam
152 # * pthread_attr_setschedpolicy
153 # * pthread_attr_setscope
154 # * pthread_attr_setstack
155 # * pthread_attr_setstackaddr
156 # * pthread_attr_setstacksize
159 private extern class NativePthreadMutex in "C" `{ pthread_mutex_t * `}
160 new (attr: NativePthreadMutexAttr) `{
161 pthread_mutex_t
*mutex
= malloc
(sizeof
(pthread_mutex_t
));
162 int res
= pthread_mutex_init
(mutex
, attr
);
166 fun destroy `{ pthread_mutex_destroy(recv); `}
168 fun lock
`{ pthread_mutex_lock(recv); `}
169 fun try_lock: Bool `{ return pthread_mutex_trylock(recv); `}
170 fun unlock
`{ pthread_mutex_unlock(recv); `}
173 private extern class NativePthreadMutexAttr in "C" `{ pthread_mutexattr_t * `}
175 pthread_mutexattr_t *attr = malloc(sizeof(pthread_mutexattr_t));
176 int res = pthread_mutexattr_init(attr);
180 fun destroy
`{ pthread_mutexattr_destroy(recv); `}
182 fun set_type_normal `{ pthread_mutexattr_settype(recv, PTHREAD_MUTEX_NORMAL); `}
183 fun set_type_recursive
`{ pthread_mutexattr_settype(recv, PTHREAD_MUTEX_RECURSIVE); `}
184 fun set_type_errorcheck `{ pthread_mutexattr_settype(recv, PTHREAD_MUTEX_ERRORCHECK); `}
186 # pthread_mutexattr_setpshared
187 # pthread_mutexattr_setprotocol
188 # pthread_mutexattr_setproceiling
189 # pthread_mutexattr_setrobust_np
192 private extern class NativePthreadKey in "C" `{ pthread_key_t * `}
194 pthread_key_t
*key
= malloc
(sizeof
(pthread_key_t
));
195 int res
= pthread_key_create
(key
, NULL);
199 fun get: nullable Object `{
200 void
*val
= pthread_getspecific
(*recv
);
201 if (val
== NULL) val
= null_Object
();
205 fun set(val: nullable Object) `{
206 pthread_setspecific
(*recv
, val
);
210 private extern class NativePthreadCond in "C" `{ pthread_cond_t * `}
213 int r = pthread_cond_init(&cond, NULL);
215 pthread_cond_t *pcond = malloc(sizeof(pthread_cond_t));
216 memmove(pcond, &cond, sizeof(pthread_cond_t));
222 fun destroy
`{ pthread_cond_destroy(recv); `}
224 fun signal `{ pthread_cond_signal(recv); `}
226 fun broadcast
`{ pthread_cond_broadcast(recv); `}
228 fun wait(mutex: NativePthreadMutex) `{ pthread_cond_wait(recv, mutex); `}
234 # Cannot be extracted from this module because of the callback from C to `Thread::run`
239 # Instances of this class are each used to launch and control a thread.
240 abstract class Thread
243 private var native
: nullable NativePthread = null
245 # Main method of this thread
247 # The returned valued is passed to the caller of `join`.
248 fun main
: nullable Object do return null
250 private fun main_intern
: nullable Object
252 # Register thread local data
253 sys
.self_thread_key
.set
self
258 # Start executing this thread
260 # Will launch `main` on a different thread.
263 if native
!= null then return
264 native
= new NativePthread.create
(self)
267 # Join this thread to the calling thread
269 # Blocks until the method `main` returns or the target thread calls
270 # `Sys::thread_exit`. Returns the object returned from the other thread.
272 # Stats the thread if now already done by a call to `start`.
273 fun join
: nullable Object
275 if native
== null then start
283 if native
== null then return
289 # The main thread of the program
296 # Exit current thread and return `value` to caller of `Thread::join`
297 fun exit_thread
(value
: nullable Object) `{ pthread_exit(value); `}
299 # Returns the handle to the running `Thread`
302 var key = sys.self_thread_key
305 # This is the original thread, get `Sys::main_thread
` and store it
306 var thread = sys.main_thread
311 assert val isa Thread
315 # Mutual exclusion synchronization tool
317 # Instances of this class can only be acquired by a single thread at any one
318 # point in time. Uses the recursive protocol so they can be locked many time by
319 # the same thread, must then be unlocked as many time.
323 private var native: nullable NativePthreadMutex is noinit
327 var attr = new NativePthreadMutexAttr
328 attr.set_type_recursive
329 native = new NativePthreadMutex(attr)
334 # Acquire this lock, wait until it is available
335 fun lock do native.lock
337 # Acquire this lock only if it is available
339 # Returns `true` if the lock has been acquired.
340 fun try_lock: Bool do return native.try_lock
342 # Release this lock, unblocking all callers of `lock
`
343 fun unlock do native.unlock
347 var native = self.native
348 if native != null then
356 # Barrier synchronization tool
358 # Ensures that `count
` threads call and block on `wait
` before releasing them.
362 private var mutex = new Mutex
363 private var cond: nullable NativePthreadCond = new NativePthreadCond
365 # Number of threads that must be waiting for `wait
` to unblock
368 private var threads_waiting = 0
370 # Wait at this barrier and block until there are a `count
` threads waiting
375 if threads_waiting == count then
379 cond.wait(mutex.native.as(not null))
395 # Print `object
` and '\n' with the same system call
396 redef fun print(object)
398 sys.stdout.write(object.to_s+"\n")