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`
27 # Nity part at the bottom of the module.
35 // TODO protect with: #ifdef WITH_LIBGC
36 // We might have to add the next line to gc_chooser.c too, especially
37 // if we get an error like "thread not registered with GC".
46 # `NativePthread` for running thread
47 private fun native_pthread_self
: NativePthread `{
48 pthread_t *id = malloc(sizeof(pthread_t));
53 private var self_thread_key
= new NativePthreadKey
55 private var main_thread_cache
: nullable MainThread = null
56 private var main_thread_mutex
= new Mutex
58 # Handle to the program's main thread
59 fun main_thread
: MainThread
61 var cache
= main_thread_cache
62 if cache
!= null then return cache
64 main_thread_mutex
.lock
66 # Recheck if cache has been updated since lock has been unlocked/locked
67 cache
= main_thread_cache
69 main_thread_mutex
.unlock
73 # Create a `MainThread` exactly once
74 var thread
= new MainThread
75 thread
.native
= sys
.native_pthread_self
76 main_thread_cache
= thread
78 main_thread_mutex
.unlock
83 private extern class NativePthread in "C" `{ pthread_t * `}
85 new create(nit_thread: Thread) import Thread.main_intern `{
87 pthread_attr_init
(&attr
);
90 int r
= pthread_create
(&thread
, &attr
, (void
* (*)(void
*))&Thread_main_intern, nit_thread
);
93 pthread_t
*pthread
= malloc
(sizeof
(pthread_t
));
94 memmove
(pthread
, &thread
, sizeof
(pthread_t
));
100 new create_ex(nit_thread: Thread, attr: NativePthreadAttr) import Thread.main_intern `{
102 int r
= pthread_create
(&thread
, attr
, (void
* (*)(void
*))&Thread_main_intern, nit_thread
);
105 pthread_t
*pthread
= malloc
(sizeof
(pthread_t
));
106 memmove
(pthread
, &thread
, sizeof
(pthread_t
));
112 fun join: nullable Object `{
114 pthread_join
(*recv
, &thread_return
);
115 if(thread_return
== NULL) thread_return
= null_Object
();
116 return (nullable_Object
)thread_return
;
119 fun equal(other: NativePthread): Bool `{ return pthread_equal(*recv, *other); `}
121 fun kill
(signal
: Int) `{ pthread_kill(*recv, signal); `}
124 private extern class NativePthreadAttr in "C" `{ pthread_attr_t * `}
127 int r = pthread_attr_init(&attr);
129 pthread_attr_t *pattr = malloc(sizeof(pthread_attr_t));
130 memmove(pattr, &attr, sizeof(pthread_attr_t));
137 pthread_attr_destroy(recv);
140 # Most features of this class are still TODO
142 # * pthread_attr_setaffinity_np(3)
143 # * pthread_attr_setdetachstate
144 # * pthread_attr_setguardsize
145 # * pthread_attr_setinheritsched
146 # * pthread_attr_setschedparam
147 # * pthread_attr_setschedpolicy
148 # * pthread_attr_setscope
149 # * pthread_attr_setstack
150 # * pthread_attr_setstackaddr
151 # * pthread_attr_setstacksize
154 private extern class NativePthreadMutex in "C" `{ pthread_mutex_t * `}
155 new (attr: NativePthreadMutexAttr) `{
156 pthread_mutex_t
*mutex
= malloc
(sizeof
(pthread_mutex_t
));
157 int res
= pthread_mutex_init
(mutex
, attr
);
161 fun destroy `{ pthread_mutex_destroy(recv); `}
163 fun lock
`{ pthread_mutex_lock(recv); `}
164 fun try_lock: Bool `{ return pthread_mutex_trylock(recv); `}
165 fun unlock
`{ pthread_mutex_unlock(recv); `}
168 private extern class NativePthreadMutexAttr in "C" `{ pthread_mutexattr_t * `}
170 pthread_mutexattr_t *attr = malloc(sizeof(pthread_mutexattr_t));
171 int res = pthread_mutexattr_init(attr);
175 fun destroy
`{ pthread_mutexattr_destroy(recv); `}
177 fun set_type_normal `{ pthread_mutexattr_settype(recv, PTHREAD_MUTEX_NORMAL); `}
178 fun set_type_recursive
`{ pthread_mutexattr_settype(recv, PTHREAD_MUTEX_RECURSIVE); `}
179 fun set_type_errorcheck `{ pthread_mutexattr_settype(recv, PTHREAD_MUTEX_ERRORCHECK); `}
181 # pthread_mutexattr_setpshared
182 # pthread_mutexattr_setprotocol
183 # pthread_mutexattr_setproceiling
184 # pthread_mutexattr_setrobust_np
187 private extern class NativePthreadKey in "C" `{ pthread_key_t * `}
189 pthread_key_t
*key
= malloc
(sizeof
(pthread_key_t
));
190 int res
= pthread_key_create
(key
, NULL);
194 fun get: nullable Object `{
195 void
*val
= pthread_getspecific
(*recv
);
196 if (val
== NULL) val
= null_Object
();
200 fun set(val: nullable Object) `{
201 pthread_setspecific
(*recv
, val
);
205 private extern class NativePthreadCond in "C" `{ pthread_cond_t * `}
208 int r = pthread_cond_init(&cond, NULL);
210 pthread_cond_t *pcond = malloc(sizeof(pthread_cond_t));
211 memmove(pcond, &cond, sizeof(pthread_cond_t));
217 fun destroy
`{ pthread_cond_destroy(recv); `}
219 fun signal `{ pthread_cond_signal(recv); `}
221 fun broadcast
`{ pthread_cond_broadcast(recv); `}
223 fun wait(mutex: NativePthreadMutex) `{ pthread_cond_wait(recv, mutex); `}
229 # Cannot be extracted from this module because of the callback from C to `Thread::run`
234 # Instances of this class are each used to launch and control a thread.
235 abstract class Thread
238 private var native
: nullable NativePthread = null
240 # Main method of this thread
242 # The returned valued is passed to the caller of `join`.
243 fun main
: nullable Object do return null
245 private fun main_intern
: nullable Object
247 # Register thread local data
248 sys
.self_thread_key
.set
self
253 # Start executing this thread
255 # Will launch `main` on a different thread.
258 if native
!= null then return
259 native
= new NativePthread.create
(self)
262 # Join this thread to the calling thread
264 # Blocks until the method `main` returns or the target thread calls
265 # `Sys::thread_exit`. Returns the object returned from the other thread.
267 # Stats the thread if now already done by a call to `start`.
268 fun join
: nullable Object
270 if native
== null then start
278 if native
== null then return
284 # The main thread of the program
291 # Exit current thread and return `value` to caller of `Thread::join`
292 fun exit_thread
(value
: nullable Object) `{ pthread_exit(value); `}
294 # Returns the handle to the running `Thread`
297 var key = sys.self_thread_key
300 # This is the original thread, get `Sys::main_thread
` and store it
301 var thread = sys.main_thread
306 assert val isa Thread
310 # Mutual exclusion synchronization tool
312 # Instances of this class can only be acquired by a single thread at any one
313 # point in time. Uses the recursive protocol so they can be locked many time by
314 # the same thread, must then be unlocked as many time.
318 private var native: nullable NativePthreadMutex is noinit
322 var attr = new NativePthreadMutexAttr
323 attr.set_type_recursive
324 native = new NativePthreadMutex(attr)
329 # Acquire this lock, wait until it is available
330 fun lock do native.lock
332 # Acquire this lock only if it is available
334 # Returns `true` if the lock has been acquired.
335 fun try_lock: Bool do return native.try_lock
337 # Release this lock, unblocking all callers of `lock
`
338 fun unlock do native.unlock
342 var native = self.native
343 if native != null then
351 # Barrier synchronization tool
353 # Ensures that `count
` threads call and block on `wait
` before releasing them.
357 private var mutex = new Mutex
358 private var cond: nullable NativePthreadCond = new NativePthreadCond
360 # Number of threads that must be waiting for `wait
` to unblock
363 private var threads_waiting = 0
365 # Wait at this barrier and block until there are a `count
` threads waiting
370 if threads_waiting == count then
374 cond.wait(mutex.native.as(not null))
390 # Print `object
` and '\n' with the same system call
391 redef fun print(object)
393 sys.stdout.write(object.to_s+"\n")