1 /* src/threads/posix/thread-posix.cpp - POSIX thread functions
3 Copyright (C) 1996-2011
4 CACAOVM - Verein zur Foerderung der freien virtuellen Maschine CACAO
6 This file is part of CACAO.
8 This program is free software; you can redistribute it and/or
9 modify it under the terms of the GNU General Public License as
10 published by the Free Software Foundation; either version 2, or (at
11 your option) any later version.
13 This program is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
28 /* XXX cleanup these includes */
30 #define __STDC_LIMIT_MACROS
35 #include <sys/types.h>
48 #include "mm/memory.hpp"
50 #if defined(ENABLE_GC_CACAO)
51 # include "mm/cacao-gc/gc.h"
54 #include "native/llni.h"
55 #include "native/native.hpp"
57 #include "threads/condition.hpp"
58 #include "threads/lock.hpp"
59 #include "threads/mutex.hpp"
60 #include "threads/threadlist.hpp"
61 #include "threads/thread.hpp"
63 #include "toolbox/logging.hpp"
65 #include "vm/jit/builtin.hpp"
66 #include "vm/exceptions.hpp"
67 #include "vm/global.h"
68 #include "vm/globals.hpp"
69 #include "vm/hook.hpp"
70 #include "vm/javaobjects.hpp"
71 #include "vm/options.h"
73 #include "vm/signallocal.hpp"
74 #include "vm/string.hpp"
77 #if defined(ENABLE_STATISTICS)
78 # include "vm/statistics.h"
81 #include "vm/jit/asmpart.h"
83 #if defined(__DARWIN__)
92 # include <semaphore.h>
95 #if defined(__LINUX__)
96 # define GC_LINUX_THREADS
97 #elif defined(__IRIX__)
98 # define GC_IRIX_THREADS
99 #elif defined(__DARWIN__)
100 # define GC_DARWIN_THREADS
101 #elif defined(__SOLARIS__)
102 # define GC_SOLARIS_THREADS
105 #if defined(ENABLE_GC_BOEHM)
106 /* We need to include Boehm's gc.h here because it overrides
107 pthread_create and friends. */
108 # include "mm/boehm-gc/include/gc.h"
112 #if defined(__DARWIN__)
113 /* Darwin has no working semaphore implementation. This one is taken
117 This is a very simple semaphore implementation for Darwin. It
118 is implemented in terms of pthreads calls so it isn't async signal
119 safe. This isn't a problem because signals aren't used to
120 suspend threads on Darwin.
123 static int sem_init(sem_t *sem, int pshared, int value)
128 sem->mutex = new Mutex();
129 sem->cond = new Condition();
135 static int sem_post(sem_t *sem)
140 sem->mutex->unlock();
145 static int sem_wait(sem_t *sem)
149 while (sem->value == 0) {
150 sem->cond->wait(sem->mutex);
154 sem->mutex->unlock();
159 static int sem_destroy(sem_t *sem)
166 #endif /* defined(__DARWIN__) */
169 /* startupinfo *****************************************************************
171 Struct used to pass info from threads_start_thread to
172 threads_startup_thread.
174 ******************************************************************************/
177 threadobject *thread; /* threadobject for this thread */
178 functionptr function; /* function to run in the new thread */
179 sem_t *psem; /* signals when thread has been entered */
180 /* in the thread list */
181 sem_t *psem_first; /* signals when pthread_create has returned */
185 /* prototypes *****************************************************************/
187 static void threads_calc_absolute_time(struct timespec *tm, s8 millis, s4 nanos);
190 /******************************************************************************/
191 /* GLOBAL VARIABLES */
192 /******************************************************************************/
194 /* the thread object of the current thread */
195 /* This is either a thread-local variable defined with __thread, or */
196 /* a thread-specific value stored with key threads_current_threadobject_key. */
197 #if defined(HAVE___THREAD)
198 __thread threadobject *thread_current;
200 pthread_key_t thread_current_key;
203 /* global mutex for stop-the-world */
204 static Mutex* stopworldlock;
206 #if defined(ENABLE_GC_CACAO)
207 /* global mutex for the GC */
208 static Mutex* mutex_gc;
211 /* global mutex and condition for joining threads on exit */
212 static Mutex* mutex_join;
213 static Condition* cond_join;
215 #if defined(ENABLE_GC_CACAO)
216 /* semaphore used for acknowleding thread suspension */
217 static sem_t suspend_ack;
221 /* threads_sem_init ************************************************************
223 Initialize a semaphore. Checks against errors and interruptions.
226 sem..............the semaphore to initialize
227 shared...........true if this semaphore will be shared between processes
228 value............the initial value for the semaphore
230 *******************************************************************************/
232 void threads_sem_init(sem_t *sem, bool shared, int value)
239 r = sem_init(sem, shared, value);
242 } while (errno == EINTR);
244 vm_abort("sem_init failed: %s", strerror(errno));
248 /* threads_sem_wait ************************************************************
250 Wait for a semaphore, non-interruptible.
252 IMPORTANT: Always use this function instead of `sem_wait` directly, as
253 `sem_wait` may be interrupted by signals!
256 sem..............the semaphore to wait on
258 *******************************************************************************/
260 void threads_sem_wait(sem_t *sem)
270 } while (errno == EINTR);
272 vm_abort("sem_wait failed: %s", strerror(errno));
276 /* threads_sem_post ************************************************************
278 Increase the count of a semaphore. Checks for errors.
281 sem..............the semaphore to increase the count of
283 *******************************************************************************/
285 void threads_sem_post(sem_t *sem)
291 /* unlike sem_wait, sem_post is not interruptible */
297 vm_abort("sem_post failed: %s", strerror(errno));
301 /* threads_stopworld ***********************************************************
303 Stops the world from turning. All threads except the calling one
304 are suspended. The function returns as soon as all threads have
305 acknowledged their suspension.
307 *******************************************************************************/
309 #if defined(ENABLE_GC_CACAO)
310 void threads_stopworld(void)
312 #if !defined(__DARWIN__) && !defined(__CYGWIN__)
319 stopworldlock->lock();
321 /* lock the threads lists */
325 #if defined(__DARWIN__)
326 /*threads_cast_darwinstop();*/
328 #elif defined(__CYGWIN__)
334 DEBUGTHREADS("stops World", self);
338 /* suspend all running threads */
339 for (t = threadlist_first(); t != NULL; t = threadlist_next(t)) {
340 /* don't send the signal to ourself */
345 /* don't send the signal to NEW threads (because they are not
346 completely initialized) */
348 if (t->state == THREAD_STATE_NEW)
351 /* send the signal */
353 result = threads_suspend_thread(t, SUSPEND_REASON_STOPWORLD);
356 /* increase threads count */
361 /* wait for all threads signaled to suspend */
362 for (i = 0; i < count; i++)
363 threads_sem_wait(&suspend_ack);
366 /* ATTENTION: Don't unlock the threads-lists here so that
367 non-signaled NEW threads can't change their state and execute
373 /* threads_startworld **********************************************************
375 Starts the world again after it has previously been stopped.
377 *******************************************************************************/
379 #if defined(ENABLE_GC_CACAO)
380 void threads_startworld(void)
382 #if !defined(__DARWIN__) && !defined(__CYGWIN__)
389 #if defined(__DARWIN__)
390 /*threads_cast_darwinresume();*/
392 #elif defined(__IRIX__)
393 threads_cast_irixresume();
394 #elif defined(__CYGWIN__)
400 DEBUGTHREADS("starts World", self);
404 /* resume all thread we haltet */
405 for (t = threadlist_first(); t != NULL; t = threadlist_next(t)) {
406 /* don't send the signal to ourself */
411 /* don't send the signal to NEW threads (because they are not
412 completely initialized) */
414 if (t->state == THREAD_STATE_NEW)
417 /* send the signal */
419 result = threads_resume_thread(t);
422 /* increase threads count */
427 /* wait for all threads signaled to suspend */
428 for (i = 0; i < count; i++)
429 threads_sem_wait(&suspend_ack);
433 /* unlock the threads lists */
437 stopworldlock->unlock();
442 /* threads_impl_thread_clear ***************************************************
444 Clears all fields in threadobject the way an MZERO would have
445 done. MZERO cannot be used anymore because it would mess up the
449 t....the threadobject
451 *******************************************************************************/
453 void threads_impl_thread_clear(threadobject *t)
462 t->is_in_active_list = false;
466 #if defined(__DARWIN__)
470 t->interrupted = false;
473 t->suspended = false;
474 t->suspend_reason = 0;
478 t->_exceptionptr = NULL;
479 t->_stackframeinfo = NULL;
480 t->_localref_table = NULL;
482 #if defined(ENABLE_INTRP)
483 t->_global_sp = NULL;
486 #if defined(ENABLE_GC_CACAO)
487 t->gc_critical = false;
493 // Simply reuse the existing dump memory.
496 /* threads_impl_thread_reuse ***************************************************
498 Resets some implementation fields in threadobject. This was
499 previously done in threads_impl_thread_new.
502 t....the threadobject
504 *******************************************************************************/
506 void threads_impl_thread_reuse(threadobject *t)
508 /* get the pthread id */
510 t->tid = pthread_self();
512 #if defined(ENABLE_DEBUG_FILTER)
513 /* Initialize filter counters */
514 t->filterverbosecallctr[0] = 0;
515 t->filterverbosecallctr[1] = 0;
519 t->tracejavacallindent = 0;
520 t->tracejavacallcount = 0;
527 /* not really needed */
528 t->flc_object = NULL;
530 #if defined(ENABLE_TLH)
531 tlh_destroy(&(t->tlh));
536 void threads_impl_clear_heap_pointers(threadobject *t)
542 /* threads_impl_preinit ********************************************************
544 Do some early initialization of stuff required.
546 ATTENTION: Do NOT use any Java heap allocation here, as gc_init()
547 is called AFTER this function!
549 *******************************************************************************/
551 void threads_impl_preinit(void)
553 stopworldlock = new Mutex();
555 /* initialize exit mutex and condition (on exit we join all
558 mutex_join = new Mutex();
559 cond_join = new Condition();
561 #if defined(ENABLE_GC_CACAO)
562 /* initialize the GC mutex & suspend semaphore */
564 mutex_gc = new Mutex();
565 threads_sem_init(&suspend_ack, 0, 0);
568 #if !defined(HAVE___THREAD)
569 int result = pthread_key_create(&thread_current_key, NULL);
571 os::abort_errnum(result, "threads_impl_preinit: pthread_key_create failed");
576 /* threads_mutex_gc_lock *******************************************************
578 Enter the global GC mutex.
580 *******************************************************************************/
582 #if defined(ENABLE_GC_CACAO)
583 void threads_mutex_gc_lock(void)
590 /* threads_mutex_gc_unlock *****************************************************
592 Leave the global GC mutex.
594 *******************************************************************************/
596 #if defined(ENABLE_GC_CACAO)
597 void threads_mutex_gc_unlock(void)
603 /* threads_mutex_join_lock *****************************************************
605 Enter the join mutex.
607 *******************************************************************************/
609 void threads_mutex_join_lock(void)
615 /* threads_mutex_join_unlock ***************************************************
617 Leave the join mutex.
619 *******************************************************************************/
621 void threads_mutex_join_unlock(void)
623 mutex_join->unlock();
627 /* threads_impl_init ***********************************************************
629 Initializes the implementation specific bits.
631 *******************************************************************************/
633 void threads_impl_init(void)
638 threads_set_thread_priority(pthread_self(), NORM_PRIORITY);
640 /* Initialize the thread attribute object. */
642 result = pthread_attr_init(&attr);
645 os::abort_errnum(result, "threads_impl_init: pthread_attr_init failed");
647 result = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
650 os::abort_errnum(result, "threads_impl_init: pthread_attr_setdetachstate failed");
654 /* threads_startup_thread ******************************************************
656 Thread startup function called by pthread_create.
658 Thread which have a startup.function != NULL are marked as internal
659 threads. All other threads are threated as normal Java threads.
661 NOTE: This function is not called directly by pthread_create. The Boehm GC
662 inserts its own GC_start_routine in between, which then calls
666 arg..........the argument passed to pthread_create, ie. a pointer to
667 a startupinfo struct. CAUTION: When the `psem` semaphore
668 is posted, the startupinfo struct becomes invalid! (It
669 is allocated on the stack of threads_start_thread.)
671 ******************************************************************************/
673 static void *threads_startup_thread(void *arg)
675 startupinfo *startup;
680 functionptr function;
682 #if defined(ENABLE_GC_BOEHM)
683 # if !defined(__DARWIN__)
684 struct GC_stack_base sb;
689 #if defined(ENABLE_INTRP)
690 u1 *intrp_thread_stack;
693 #if defined(ENABLE_INTRP)
694 /* create interpreter stack */
697 intrp_thread_stack = GCMNEW(u1, opt_stacksize);
698 MSET(intrp_thread_stack, 0, u1, opt_stacksize);
701 intrp_thread_stack = NULL;
704 /* get passed startupinfo structure and the values in there */
706 startup = (startupinfo*) arg;
709 function = startup->function;
710 psem = startup->psem;
712 /* Seems like we've encountered a situation where thread->tid was
713 not set by pthread_create. We alleviate this problem by waiting
714 for pthread_create to return. */
716 threads_sem_wait(startup->psem_first);
718 #if defined(__DARWIN__)
719 t->mach_thread = mach_thread_self();
722 /* Now that we are in the new thread, we can store the internal
723 thread data-structure in the TSD. */
725 thread_set_current(t);
727 #if defined(ENABLE_GC_BOEHM)
728 # if defined(__DARWIN__)
729 // This is currently not implemented in Boehm-GC. Just fail silently.
731 /* Register the thread with Boehm-GC. This must happen before the
732 thread allocates any memory from the GC heap.*/
734 result = GC_get_stack_base(&sb);
737 vm_abort("threads_startup_thread: GC_get_stack_base failed: result=%d", result);
739 GC_register_my_thread(&sb);
743 // Get the java.lang.Thread object for this thread.
744 java_handle_t* object = thread_get_object(t);
745 java_lang_Thread jlt(object);
747 /* set our priority */
749 threads_set_thread_priority(t->tid, jlt.get_priority());
751 /* Thread is completely initialized. */
753 thread_set_state_runnable(t);
755 /* tell threads_startup_thread that we registered ourselves */
756 /* CAUTION: *startup becomes invalid with this! */
759 threads_sem_post(psem);
761 #if defined(ENABLE_INTRP)
762 /* set interpreter stack */
765 thread->_global_sp = (Cell *) (intrp_thread_stack + opt_stacksize);
768 // Hook point just before the threads initial method is executed.
769 Hook::thread_start(t);
771 DEBUGTHREADS("starting", t);
773 /* find and run the Thread.run()V method if no other function was passed */
775 if (function == NULL) {
776 c = ThreadRuntime::get_thread_class_from_object(object);
778 m = class_resolveclassmethod(c, utf_run, utf_void__void, c, true);
781 vm_abort("threads_startup_thread: run() method not found in class");
783 java_handle_t *h = ThreadRuntime::get_vmthread_handle(jlt);
785 /* Run the thread. */
787 (void) vm_call_method(m, h);
790 /* call passed function, e.g. finalizer_thread */
795 DEBUGTHREADS("stopping", t);
797 // Hook point just after the threads initial method returned.
800 /* We ignore the return value. */
802 (void) thread_detach_current_thread();
808 /* threads_impl_thread_start ***************************************************
810 Start a thread in the JVM. Both (vm internal and java) thread
814 thread....the thread object
815 f.........function to run in the new thread. NULL means that the
816 "run" method of the object `t` should be called
818 ******************************************************************************/
820 void threads_impl_thread_start(threadobject *thread, functionptr f)
828 /* fill startupinfo structure passed by pthread_create to
829 * threads_startup_thread */
831 startup.thread = thread;
832 startup.function = f; /* maybe we don't call Thread.run()V */
834 startup.psem_first = &sem_first;
836 threads_sem_init(&sem, 0, 0);
837 threads_sem_init(&sem_first, 0, 0);
839 /* Initialize thread attributes. */
841 result = pthread_attr_init(&attr);
844 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_init failed");
846 result = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
849 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_setdetachstate failed");
851 /* initialize thread stacksize */
853 result = pthread_attr_setstacksize(&attr, opt_stacksize);
856 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_setstacksize failed");
858 /* create the thread */
860 result = pthread_create(&(thread->tid), &attr, threads_startup_thread, &startup);
863 os::abort_errnum(result, "threads_impl_thread_start: pthread_create failed");
865 /* destroy the thread attributes */
867 result = pthread_attr_destroy(&attr);
870 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_destroy failed");
872 /* signal that pthread_create has returned, so thread->tid is valid */
874 threads_sem_post(&sem_first);
876 /* wait here until the thread has entered itself into the thread list */
878 threads_sem_wait(&sem);
883 sem_destroy(&sem_first);
887 /* threads_set_thread_priority *************************************************
889 Set the priority of the given thread.
892 tid..........thread id
893 priority.....priority to set
895 ******************************************************************************/
897 void threads_set_thread_priority(pthread_t tid, int priority)
899 struct sched_param schedp;
902 pthread_getschedparam(tid, &policy, &schedp);
903 schedp.sched_priority = priority;
904 pthread_setschedparam(tid, policy, &schedp);
909 * Detaches the current thread from the VM.
911 * @return true on success, false otherwise
913 bool thread_detach_current_thread(void)
915 threadobject* t = thread_get_current();
921 /* If the given thread has already been detached, this operation
924 if (thread_is_attached(t) == false)
927 DEBUGTHREADS("detaching", t);
929 java_handle_t* object = thread_get_object(t);
930 java_lang_Thread jlt(object);
932 #if defined(ENABLE_JAVASE)
933 java_handle_t* group = jlt.get_group();
935 /* If there's an uncaught exception, call uncaughtException on the
936 thread's exception handler, or the thread's group if this is
939 java_handle_t* e = exceptions_get_and_clear_exception();
942 /* We use the type void* for handler here, as it's not trivial
943 to build the java_lang_Thread_UncaughtExceptionHandler
944 header file with cacaoh. */
946 java_handle_t *handler = ThreadRuntime::get_thread_exception_handler(jlt);
951 if (handler != NULL) {
952 LLNI_class_get(handler, c);
953 h = (java_handle_t *) handler;
956 LLNI_class_get(group, c);
957 h = (java_handle_t *) group;
960 methodinfo* m = class_resolveclassmethod(c,
961 utf_uncaughtException,
962 utf_java_lang_Thread_java_lang_Throwable__V,
969 (void) vm_call_method(m, h, object, e);
971 if (exceptions_get_exception())
975 /* XXX TWISTI: should all threads be in a ThreadGroup? */
977 /* Remove thread from the thread group. */
981 LLNI_class_get(group, c);
983 methodinfo *m = ThreadRuntime::get_threadgroup_remove_method(c);
988 (void) vm_call_method(m, group, object);
990 if (exceptions_get_exception())
993 // Clear the ThreadGroup in the Java thread object (Mauve
994 // test: gnu/testlet/java/lang/Thread/getThreadGroup).
999 /* Thread has terminated. */
1001 thread_set_state_terminated(t);
1003 /* Notify all threads waiting on this thread. These are joining
1006 /* XXX Care about exceptions? */
1007 (void) lock_monitor_enter(jlt.get_handle());
1009 lock_notify_all_object(jlt.get_handle());
1011 /* XXX Care about exceptions? */
1012 (void) lock_monitor_exit(jlt.get_handle());
1014 t->waitmutex->lock();
1016 t->waitmutex->unlock();
1018 /* Enter the join-mutex before calling thread_free, so
1019 threads_join_all_threads gets the correct number of non-daemon
1022 threads_mutex_join_lock();
1024 /* Free the internal thread data-structure. */
1028 /* Signal that this thread has finished and leave the mutex. */
1030 cond_join->signal();
1031 threads_mutex_join_unlock();
1033 t->suspendmutex->lock();
1034 t->suspendmutex->unlock();
1041 * Internal helper function which suspends the current thread. This is
1042 * the core method of the suspension mechanism actually blocking the
1043 * execution until the suspension reason is cleared again. Note that
1044 * the current thread needs to hold the suspension mutex while calling
1047 static void threads_suspend_self()
1049 threadobject* thread = THREADOBJECT;
1051 DEBUGTHREADS("suspending", thread);
1053 // Mark thread as suspended.
1054 assert(!thread->suspended);
1055 assert(thread->suspend_reason != SUSPEND_REASON_NONE);
1056 thread->suspended = true;
1058 // Acknowledge the suspension.
1059 thread->suspendcond->broadcast();
1061 #if defined(ENABLE_GC_CACAO)
1062 // If we are stopping the world, we should send a global ack.
1063 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD)
1064 threads_sem_post(&suspend_ack);
1067 // Release the suspension mutex and wait till we are resumed.
1068 while (thread->suspend_reason != SUSPEND_REASON_NONE)
1069 thread->suspendcond->wait(thread->suspendmutex);
1071 #if defined(ENABLE_GC_CACAO)
1072 // XXX This is propably not ok!
1073 // If we are starting the world, we should send a global ack.
1074 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD)
1075 threads_sem_post(&suspend_ack);
1078 // Mark thread as not suspended.
1079 assert(thread->suspended);
1080 assert(thread->suspend_reason == SUSPEND_REASON_NONE);
1081 thread->suspended = false;
1083 DEBUGTHREADS("resuming", thread);
1088 * Suspend the passed thread. Execution of that thread stops until the thread
1089 * is explicitly resumed again.
1091 * @param thread The thread to be suspended.
1092 * @param reason Reason for suspending the given thread.
1093 * @return True of operation was successful, false otherwise.
1095 bool threads_suspend_thread(threadobject *thread, int32_t reason)
1098 assert(reason != SUSPEND_REASON_NONE);
1100 // Guard this with the suspension mutex.
1101 MutexLocker ml(*thread->suspendmutex);
1103 // Check if thread is already suspended.
1104 if (thread->suspended)
1107 // Check if thread is in the process of suspending.
1108 if (thread->suspend_reason != SUSPEND_REASON_NONE)
1111 // Set the reason for suspending the thread.
1112 thread->suspend_reason = reason;
1114 if (thread == THREADOBJECT) {
1115 // We already hold the suspension mutex and can suspend ourselves
1116 // immediately without using signals at all.
1117 threads_suspend_self();
1120 // Send the suspend signal to the other thread.
1123 if (pthread_kill(thread->tid, SIGUSR1) != 0)
1124 os::abort_errno("threads_suspend_thread: pthread_kill failed");
1126 // Wait for the thread to acknowledge the suspension.
1127 while (!thread->suspended)
1128 thread->suspendcond->wait(thread->suspendmutex);
1136 * Resumes execution of the passed thread.
1138 * @param thread The thread to be resumed.
1139 * @param reason Reason for suspending the given thread.
1140 * @return True of operation was successful, false otherwise.
1142 bool threads_resume_thread(threadobject *thread, int32_t reason)
1145 assert(thread != THREADOBJECT);
1146 assert(reason != SUSPEND_REASON_NONE);
1148 // Guard this with the suspension mutex.
1149 MutexLocker ml(*thread->suspendmutex);
1151 // Check if thread really is suspended.
1152 if (!thread->suspended)
1155 // Threads can only be resumed for the same reason they were suspended.
1156 if (thread->suspend_reason != reason)
1159 // Clear the reason for suspending the thread.
1160 thread->suspend_reason = SUSPEND_REASON_NONE;
1162 // Tell everyone that the thread should resume.
1163 thread->suspendcond->broadcast();
1170 * Acknowledges the suspension of the current thread.
1172 void threads_suspend_ack()
1174 threadobject* thread = THREADOBJECT;
1176 // Guard this with the suspension mutex.
1177 MutexLocker ml(*thread->suspendmutex);
1179 // Suspend ourselves while holding the suspension mutex.
1180 threads_suspend_self();
1184 /* threads_join_all_threads ****************************************************
1186 Join all non-daemon threads.
1188 *******************************************************************************/
1190 void threads_join_all_threads(void)
1194 /* get current thread */
1198 /* This thread is waiting for all non-daemon threads to exit. */
1200 thread_set_state_waiting(t);
1202 /* enter join mutex */
1204 threads_mutex_join_lock();
1206 /* Wait for condition as long as we have non-daemon threads. We
1207 compare against 1 because the current (main thread) is also a
1208 non-daemon thread. */
1210 while (ThreadList::get_number_of_non_daemon_threads() > 1)
1211 cond_join->wait(mutex_join);
1213 /* leave join mutex */
1215 threads_mutex_join_unlock();
1219 /* threads_timespec_earlier ****************************************************
1221 Return true if timespec tv1 is earlier than timespec tv2.
1224 tv1..........first timespec
1225 tv2..........second timespec
1228 true, if the first timespec is earlier
1230 *******************************************************************************/
1232 static inline bool threads_timespec_earlier(const struct timespec *tv1,
1233 const struct timespec *tv2)
1235 return (tv1->tv_sec < tv2->tv_sec)
1237 (tv1->tv_sec == tv2->tv_sec && tv1->tv_nsec < tv2->tv_nsec);
1241 /* threads_current_time_is_earlier_than ****************************************
1243 Check if the current time is earlier than the given timespec.
1246 tv...........the timespec to compare against
1249 true, if the current time is earlier
1251 *******************************************************************************/
1253 static bool threads_current_time_is_earlier_than(const struct timespec *tv)
1255 struct timeval tvnow;
1256 struct timespec tsnow;
1258 /* get current time */
1260 if (gettimeofday(&tvnow, NULL) != 0)
1261 vm_abort("gettimeofday failed: %s\n", strerror(errno));
1263 /* convert it to a timespec */
1265 tsnow.tv_sec = tvnow.tv_sec;
1266 tsnow.tv_nsec = tvnow.tv_usec * 1000;
1268 /* compare current time with the given timespec */
1270 return threads_timespec_earlier(&tsnow, tv);
1274 /* threads_wait_with_timeout ***************************************************
1276 Wait until the given point in time on a monitor until either
1277 we are notified, we are interrupted, or the time is up.
1280 t............the current thread
1281 wakeupTime...absolute (latest) wakeup time
1282 If both tv_sec and tv_nsec are zero, this function
1283 waits for an unlimited amount of time.
1285 *******************************************************************************/
1287 static void threads_wait_with_timeout(threadobject *t, struct timespec *wakeupTime, bool parking)
1289 // Acquire the waitmutex.
1290 t->waitmutex->lock();
1292 /* wait on waitcond */
1294 if (wakeupTime->tv_sec || wakeupTime->tv_nsec) {
1296 while (!t->interrupted && !(parking ? t->park_permit : t->signaled)
1297 && threads_current_time_is_earlier_than(wakeupTime))
1300 thread_set_state_timed_parked(t);
1302 thread_set_state_timed_waiting(t);
1304 t->waitcond->timedwait(t->waitmutex, wakeupTime);
1306 thread_set_state_runnable(t);
1311 while (!t->interrupted && !(parking ? t->park_permit : t->signaled)) {
1313 thread_set_state_parked(t);
1315 thread_set_state_waiting(t);
1317 t->waitcond->wait(t->waitmutex);
1319 thread_set_state_runnable(t);
1324 t->park_permit = false;
1326 // Release the waitmutex.
1327 t->waitmutex->unlock();
1331 /* threads_wait_with_timeout_relative ******************************************
1333 Wait for the given maximum amount of time on a monitor until either
1334 we are notified, we are interrupted, or the time is up.
1337 t............the current thread
1338 millis.......milliseconds to wait
1339 nanos........nanoseconds to wait
1341 *******************************************************************************/
1343 void threads_wait_with_timeout_relative(threadobject *thread, s8 millis,
1346 struct timespec wakeupTime;
1348 /* calculate the the (latest) wakeup time */
1350 threads_calc_absolute_time(&wakeupTime, millis, nanos);
1354 threads_wait_with_timeout(thread, &wakeupTime, false);
1358 /* threads_calc_absolute_time **************************************************
1360 Calculate the absolute point in time a given number of ms and ns from now.
1363 millis............milliseconds from now
1364 nanos.............nanoseconds from now
1367 *tm...............receives the timespec of the absolute point in time
1369 *******************************************************************************/
1371 static void threads_calc_absolute_time(struct timespec *tm, s8 millis, s4 nanos)
1373 // (at least with GNU classpath) we know that 0 <= nanos <= 999999
1375 if (!millis && !nanos)
1378 gettimeofday(&tv, NULL);
1379 s8 secs = tv.tv_sec + millis / 1000;
1380 if (secs > INT32_MAX) // integer overflow
1384 long nsec = tv.tv_usec * 1000 + (s4) millis * 1000000 + nanos;
1385 tm->tv_sec = tv.tv_sec + nsec / 1000000000;
1386 if (tm->tv_sec < tv.tv_sec) // integer overflow
1388 tm->tv_nsec = nsec % 1000000000;
1396 /* threads_thread_interrupt ****************************************************
1398 Interrupt the given thread.
1400 The thread gets the "waitcond" signal and
1401 its interrupted flag is set to true.
1404 thread............the thread to interrupt
1406 *******************************************************************************/
1408 void threads_thread_interrupt(threadobject *t)
1410 /* Signal the thread a "waitcond" and tell it that it has been
1413 t->waitmutex->lock();
1415 DEBUGTHREADS("interrupted", t);
1417 /* Interrupt blocking system call using a signal. */
1420 pthread_kill(t->tid, Signal_INTERRUPT_SYSTEM_CALL);
1422 t->waitcond->signal();
1424 t->interrupted = true;
1426 t->waitmutex->unlock();
1431 * Sleep the current thread for the specified amount of time.
1433 * @param millis Milliseconds to sleep.
1434 * @param nanos Nanoseconds to sleep.
1436 void threads_sleep(int64_t millis, int32_t nanos)
1439 struct timespec wakeupTime;
1443 /* exceptions_throw_illegalargumentexception("timeout value is negative"); */
1444 exceptions_throw_illegalargumentexception();
1448 t = thread_get_current();
1450 if (thread_is_interrupted(t) && !exceptions_get_exception()) {
1451 /* Clear interrupted flag (Mauve test:
1452 gnu/testlet/java/lang/Thread/interrupt). */
1454 thread_set_interrupted(t, false);
1456 /* exceptions_throw_interruptedexception("sleep interrupted"); */
1457 exceptions_throw_interruptedexception();
1461 // (Note taken from classpath/vm/reference/java/lang/VMThread.java (sleep))
1462 // Note: JDK treats a zero length sleep is like Thread.yield(),
1463 // without checking the interrupted status of the thread. It's
1464 // unclear if this is a bug in the implementation or the spec.
1465 // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6213203 */
1466 if (millis == 0 && nanos == 0) {
1470 threads_calc_absolute_time(&wakeupTime, millis, nanos);
1472 threads_wait_with_timeout(t, &wakeupTime, false);
1474 interrupted = thread_is_interrupted(t);
1477 thread_set_interrupted(t, false);
1479 // An other exception could have been thrown
1480 // (e.g. ThreadDeathException).
1481 if (!exceptions_get_exception())
1482 exceptions_throw_interruptedexception();
1488 * Park the current thread for the specified amount of time or until a
1489 * specified deadline.
1491 * @param absolute Is the time in nanos a deadline or a duration?
1492 * @param nanos Nanoseconds to park (absolute=false)
1493 * or deadline in milliseconds (absolute=true)
1495 void threads_park(bool absolute, int64_t nanos)
1498 struct timespec wakeupTime;
1500 t = thread_get_current();
1503 wakeupTime.tv_nsec = 0;
1504 wakeupTime.tv_sec = nanos / 1000; /* milliseconds */
1507 threads_calc_absolute_time(&wakeupTime, nanos / 1000000, nanos % 1000000);
1509 threads_wait_with_timeout(t, &wakeupTime, true);
1513 * Unpark the specified thread.
1515 * @param t The thread to unpark.
1517 void threads_unpark(threadobject *t)
1519 t->waitmutex->lock();
1521 t->waitcond->signal();
1523 t->park_permit = true;
1525 t->waitmutex->unlock();
1529 /* threads_yield ***************************************************************
1531 Yield to the scheduler.
1533 *******************************************************************************/
1535 void threads_yield(void)
1540 #if defined(ENABLE_TLH)
1542 void threads_tlh_add_frame() {
1543 tlh_add_frame(&(THREADOBJECT->tlh));
1546 void threads_tlh_remove_frame() {
1547 tlh_remove_frame(&(THREADOBJECT->tlh));
1554 * These are local overrides for various environment variables in Emacs.
1555 * Please do not remove this and leave it at the end of the file, where
1556 * Emacs will automagically detect them.
1557 * ---------------------------------------------------------------------
1560 * indent-tabs-mode: t
1564 * vim:noexpandtab:sw=4:ts=4: