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)
465 #if defined(__DARWIN__)
469 t->interrupted = false;
472 t->suspended = false;
473 t->suspend_reason = 0;
477 t->_exceptionptr = NULL;
478 t->_stackframeinfo = NULL;
479 t->_localref_table = NULL;
481 #if defined(ENABLE_INTRP)
482 t->_global_sp = NULL;
485 #if defined(ENABLE_GC_CACAO)
486 t->gc_critical = false;
492 // Simply reuse the existing dump memory.
495 /* threads_impl_thread_reuse ***************************************************
497 Resets some implementation fields in threadobject. This was
498 previously done in threads_impl_thread_new.
501 t....the threadobject
503 *******************************************************************************/
505 void threads_impl_thread_reuse(threadobject *t)
507 /* get the pthread id */
509 t->tid = pthread_self();
511 #if defined(ENABLE_DEBUG_FILTER)
512 /* Initialize filter counters */
513 t->filterverbosecallctr[0] = 0;
514 t->filterverbosecallctr[1] = 0;
518 t->tracejavacallindent = 0;
519 t->tracejavacallcount = 0;
526 /* not really needed */
527 t->flc_object = NULL;
529 #if defined(ENABLE_TLH)
530 tlh_destroy(&(t->tlh));
536 /* threads_impl_preinit ********************************************************
538 Do some early initialization of stuff required.
540 ATTENTION: Do NOT use any Java heap allocation here, as gc_init()
541 is called AFTER this function!
543 *******************************************************************************/
545 void threads_impl_preinit(void)
547 stopworldlock = new Mutex();
549 /* initialize exit mutex and condition (on exit we join all
552 mutex_join = new Mutex();
553 cond_join = new Condition();
555 #if defined(ENABLE_GC_CACAO)
556 /* initialize the GC mutex & suspend semaphore */
558 mutex_gc = new Mutex();
559 threads_sem_init(&suspend_ack, 0, 0);
562 #if !defined(HAVE___THREAD)
563 int result = pthread_key_create(&thread_current_key, NULL);
565 os::abort_errnum(result, "threads_impl_preinit: pthread_key_create failed");
570 /* threads_mutex_gc_lock *******************************************************
572 Enter the global GC mutex.
574 *******************************************************************************/
576 #if defined(ENABLE_GC_CACAO)
577 void threads_mutex_gc_lock(void)
584 /* threads_mutex_gc_unlock *****************************************************
586 Leave the global GC mutex.
588 *******************************************************************************/
590 #if defined(ENABLE_GC_CACAO)
591 void threads_mutex_gc_unlock(void)
597 /* threads_mutex_join_lock *****************************************************
599 Enter the join mutex.
601 *******************************************************************************/
603 void threads_mutex_join_lock(void)
609 /* threads_mutex_join_unlock ***************************************************
611 Leave the join mutex.
613 *******************************************************************************/
615 void threads_mutex_join_unlock(void)
617 mutex_join->unlock();
621 /* threads_impl_init ***********************************************************
623 Initializes the implementation specific bits.
625 *******************************************************************************/
627 void threads_impl_init(void)
632 threads_set_thread_priority(pthread_self(), NORM_PRIORITY);
634 /* Initialize the thread attribute object. */
636 result = pthread_attr_init(&attr);
639 os::abort_errnum(result, "threads_impl_init: pthread_attr_init failed");
641 result = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
644 os::abort_errnum(result, "threads_impl_init: pthread_attr_setdetachstate failed");
648 /* threads_startup_thread ******************************************************
650 Thread startup function called by pthread_create.
652 Thread which have a startup.function != NULL are marked as internal
653 threads. All other threads are threated as normal Java threads.
655 NOTE: This function is not called directly by pthread_create. The Boehm GC
656 inserts its own GC_start_routine in between, which then calls
660 arg..........the argument passed to pthread_create, ie. a pointer to
661 a startupinfo struct. CAUTION: When the `psem` semaphore
662 is posted, the startupinfo struct becomes invalid! (It
663 is allocated on the stack of threads_start_thread.)
665 ******************************************************************************/
667 static void *threads_startup_thread(void *arg)
669 startupinfo *startup;
674 functionptr function;
676 #if defined(ENABLE_GC_BOEHM)
677 # if !defined(__DARWIN__)
678 struct GC_stack_base sb;
683 #if defined(ENABLE_INTRP)
684 u1 *intrp_thread_stack;
687 #if defined(ENABLE_INTRP)
688 /* create interpreter stack */
691 intrp_thread_stack = GCMNEW(u1, opt_stacksize);
692 MSET(intrp_thread_stack, 0, u1, opt_stacksize);
695 intrp_thread_stack = NULL;
698 /* get passed startupinfo structure and the values in there */
700 startup = (startupinfo*) arg;
703 function = startup->function;
704 psem = startup->psem;
706 /* Seems like we've encountered a situation where thread->tid was
707 not set by pthread_create. We alleviate this problem by waiting
708 for pthread_create to return. */
710 threads_sem_wait(startup->psem_first);
712 #if defined(__DARWIN__)
713 t->mach_thread = mach_thread_self();
716 /* Now that we are in the new thread, we can store the internal
717 thread data-structure in the TSD. */
719 thread_set_current(t);
721 #if defined(ENABLE_GC_BOEHM)
722 # if defined(__DARWIN__)
723 // This is currently not implemented in Boehm-GC. Just fail silently.
725 /* Register the thread with Boehm-GC. This must happen before the
726 thread allocates any memory from the GC heap.*/
728 result = GC_get_stack_base(&sb);
731 vm_abort("threads_startup_thread: GC_get_stack_base failed: result=%d", result);
733 GC_register_my_thread(&sb);
737 // Get the java.lang.Thread object for this thread.
738 java_handle_t* object = thread_get_object(t);
739 java_lang_Thread jlt(object);
741 /* set our priority */
743 threads_set_thread_priority(t->tid, jlt.get_priority());
745 /* Thread is completely initialized. */
747 thread_set_state_runnable(t);
749 /* tell threads_startup_thread that we registered ourselves */
750 /* CAUTION: *startup becomes invalid with this! */
753 threads_sem_post(psem);
755 #if defined(ENABLE_INTRP)
756 /* set interpreter stack */
759 thread->_global_sp = (Cell *) (intrp_thread_stack + opt_stacksize);
762 // Hook point just before the threads initial method is executed.
763 Hook::thread_start(t);
765 DEBUGTHREADS("starting", t);
767 /* find and run the Thread.run()V method if no other function was passed */
769 if (function == NULL) {
770 c = ThreadRuntime::get_thread_class_from_object(object);
772 m = class_resolveclassmethod(c, utf_run, utf_void__void, c, true);
775 vm_abort("threads_startup_thread: run() method not found in class");
777 java_handle_t *h = ThreadRuntime::get_vmthread_handle(jlt);
779 /* Run the thread. */
781 (void) vm_call_method(m, h);
784 /* call passed function, e.g. finalizer_thread */
789 DEBUGTHREADS("stopping", t);
791 // Hook point just after the threads initial method returned.
794 /* We ignore the return value. */
796 (void) thread_detach_current_thread();
802 /* threads_impl_thread_start ***************************************************
804 Start a thread in the JVM. Both (vm internal and java) thread
808 thread....the thread object
809 f.........function to run in the new thread. NULL means that the
810 "run" method of the object `t` should be called
812 ******************************************************************************/
814 void threads_impl_thread_start(threadobject *thread, functionptr f)
822 /* fill startupinfo structure passed by pthread_create to
823 * threads_startup_thread */
825 startup.thread = thread;
826 startup.function = f; /* maybe we don't call Thread.run()V */
828 startup.psem_first = &sem_first;
830 threads_sem_init(&sem, 0, 0);
831 threads_sem_init(&sem_first, 0, 0);
833 /* Initialize thread attributes. */
835 result = pthread_attr_init(&attr);
838 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_init failed");
840 result = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
843 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_setdetachstate failed");
845 /* initialize thread stacksize */
847 result = pthread_attr_setstacksize(&attr, opt_stacksize);
850 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_setstacksize failed");
852 /* create the thread */
854 result = pthread_create(&(thread->tid), &attr, threads_startup_thread, &startup);
857 os::abort_errnum(result, "threads_impl_thread_start: pthread_create failed");
859 /* destroy the thread attributes */
861 result = pthread_attr_destroy(&attr);
864 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_destroy failed");
866 /* signal that pthread_create has returned, so thread->tid is valid */
868 threads_sem_post(&sem_first);
870 /* wait here until the thread has entered itself into the thread list */
872 threads_sem_wait(&sem);
877 sem_destroy(&sem_first);
881 /* threads_set_thread_priority *************************************************
883 Set the priority of the given thread.
886 tid..........thread id
887 priority.....priority to set
889 ******************************************************************************/
891 void threads_set_thread_priority(pthread_t tid, int priority)
893 struct sched_param schedp;
896 pthread_getschedparam(tid, &policy, &schedp);
897 schedp.sched_priority = priority;
898 pthread_setschedparam(tid, policy, &schedp);
903 * Detaches the current thread from the VM.
905 * @return true on success, false otherwise
907 bool thread_detach_current_thread(void)
909 threadobject* t = thread_get_current();
915 /* If the given thread has already been detached, this operation
918 if (thread_is_attached(t) == false)
921 DEBUGTHREADS("detaching", t);
923 java_handle_t* object = thread_get_object(t);
924 java_lang_Thread jlt(object);
926 #if defined(ENABLE_JAVASE)
927 java_handle_t* group = jlt.get_group();
929 /* If there's an uncaught exception, call uncaughtException on the
930 thread's exception handler, or the thread's group if this is
933 java_handle_t* e = exceptions_get_and_clear_exception();
936 /* We use the type void* for handler here, as it's not trivial
937 to build the java_lang_Thread_UncaughtExceptionHandler
938 header file with cacaoh. */
940 java_handle_t *handler = ThreadRuntime::get_thread_exception_handler(jlt);
945 if (handler != NULL) {
946 LLNI_class_get(handler, c);
947 h = (java_handle_t *) handler;
950 LLNI_class_get(group, c);
951 h = (java_handle_t *) group;
954 methodinfo* m = class_resolveclassmethod(c,
955 utf_uncaughtException,
956 utf_java_lang_Thread_java_lang_Throwable__V,
963 (void) vm_call_method(m, h, object, e);
965 if (exceptions_get_exception())
969 /* XXX TWISTI: should all threads be in a ThreadGroup? */
971 /* Remove thread from the thread group. */
975 LLNI_class_get(group, c);
977 methodinfo *m = ThreadRuntime::get_threadgroup_remove_method(c);
982 (void) vm_call_method(m, group, object);
984 if (exceptions_get_exception())
987 // Clear the ThreadGroup in the Java thread object (Mauve
988 // test: gnu/testlet/java/lang/Thread/getThreadGroup).
993 /* Thread has terminated. */
995 thread_set_state_terminated(t);
997 /* Notify all threads waiting on this thread. These are joining
1000 /* XXX Care about exceptions? */
1001 (void) lock_monitor_enter(jlt.get_handle());
1003 lock_notify_all_object(jlt.get_handle());
1005 /* XXX Care about exceptions? */
1006 (void) lock_monitor_exit(jlt.get_handle());
1008 /* Enter the join-mutex before calling thread_free, so
1009 threads_join_all_threads gets the correct number of non-daemon
1012 threads_mutex_join_lock();
1014 /* Free the internal thread data-structure. */
1018 /* Signal that this thread has finished and leave the mutex. */
1020 cond_join->signal();
1021 threads_mutex_join_unlock();
1028 * Internal helper function which suspends the current thread. This is
1029 * the core method of the suspension mechanism actually blocking the
1030 * execution until the suspension reason is cleared again. Note that
1031 * the current thread needs to hold the suspension mutex while calling
1034 static void threads_suspend_self()
1036 threadobject* thread = THREADOBJECT;
1038 DEBUGTHREADS("suspending", thread);
1040 // Mark thread as suspended.
1041 assert(!thread->suspended);
1042 assert(thread->suspend_reason != SUSPEND_REASON_NONE);
1043 thread->suspended = true;
1045 // Acknowledge the suspension.
1046 thread->suspendcond->broadcast();
1048 #if defined(ENABLE_GC_CACAO)
1049 // If we are stopping the world, we should send a global ack.
1050 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD)
1051 threads_sem_post(&suspend_ack);
1054 // Release the suspension mutex and wait till we are resumed.
1055 thread->suspendcond->wait(thread->suspendmutex);
1057 #if defined(ENABLE_GC_CACAO)
1058 // XXX This is propably not ok!
1059 // If we are starting the world, we should send a global ack.
1060 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD)
1061 threads_sem_post(&suspend_ack);
1064 // Mark thread as not suspended.
1065 assert(thread->suspended);
1066 assert(thread->suspend_reason == SUSPEND_REASON_NONE);
1067 thread->suspended = false;
1069 DEBUGTHREADS("resuming", thread);
1074 * Suspend the passed thread. Execution of that thread stops until the thread
1075 * is explicitly resumend again.
1077 * @param thread The thread to be suspended.
1078 * @param reason Reason for suspending the given thread.
1079 * @return True of operation was successful, false otherwise.
1081 bool threads_suspend_thread(threadobject *thread, int32_t reason)
1084 assert(reason != SUSPEND_REASON_NONE);
1086 // Guard this with the suspension mutex.
1087 MutexLocker ml(*thread->suspendmutex);
1089 // Check if thread is already suspended.
1090 if (thread->suspended)
1093 // Check if thread is in the process of suspending.
1094 if (thread->suspend_reason != SUSPEND_REASON_NONE)
1097 // Set the reason for suspending the thread.
1098 thread->suspend_reason = reason;
1100 if (thread == THREADOBJECT) {
1101 // We already hold the suspension mutex and can suspend ourselves
1102 // immediately without using signals at all.
1103 threads_suspend_self();
1106 // Send the suspend signal to the other thread.
1107 if (pthread_kill(thread->tid, SIGUSR1) != 0)
1108 os::abort_errno("threads_suspend_thread: pthread_kill failed");
1110 // Wait for the thread to acknowledge the suspension.
1111 // XXX A possible optimization would be to not wait here, but you
1112 // better think this through twice before trying it!
1113 thread->suspendcond->wait(thread->suspendmutex);
1121 * Resumes execution of the passed thread.
1123 * @param thread The thread to be resumed.
1124 * @param reason Reason for suspending the given thread.
1125 * @return True of operation was successful, false otherwise.
1127 bool threads_resume_thread(threadobject *thread, int32_t reason)
1130 assert(thread != THREADOBJECT);
1131 assert(reason != SUSPEND_REASON_NONE);
1133 // Guard this with the suspension mutex.
1134 MutexLocker ml(*thread->suspendmutex);
1136 // Check if thread really is suspended.
1137 if (!thread->suspended)
1140 // Threads can only be resumed for the same reason they were suspended.
1141 if (thread->suspend_reason != reason)
1144 // Clear the reason for suspending the thread.
1145 thread->suspend_reason = SUSPEND_REASON_NONE;
1147 // Tell everyone that the thread should resume.
1148 thread->suspendcond->broadcast();
1155 * Acknowledges the suspension of the current thread.
1157 void threads_suspend_ack()
1159 threadobject* thread = THREADOBJECT;
1161 // Guard this with the suspension mutex.
1162 MutexLocker ml(*thread->suspendmutex);
1164 // Suspend ourselves while holding the suspension mutex.
1165 threads_suspend_self();
1169 /* threads_join_all_threads ****************************************************
1171 Join all non-daemon threads.
1173 *******************************************************************************/
1175 void threads_join_all_threads(void)
1179 /* get current thread */
1183 /* This thread is waiting for all non-daemon threads to exit. */
1185 thread_set_state_waiting(t);
1187 /* enter join mutex */
1189 threads_mutex_join_lock();
1191 /* Wait for condition as long as we have non-daemon threads. We
1192 compare against 1 because the current (main thread) is also a
1193 non-daemon thread. */
1195 while (ThreadList::get_number_of_non_daemon_threads() > 1)
1196 cond_join->wait(mutex_join);
1198 /* leave join mutex */
1200 threads_mutex_join_unlock();
1204 /* threads_timespec_earlier ****************************************************
1206 Return true if timespec tv1 is earlier than timespec tv2.
1209 tv1..........first timespec
1210 tv2..........second timespec
1213 true, if the first timespec is earlier
1215 *******************************************************************************/
1217 static inline bool threads_timespec_earlier(const struct timespec *tv1,
1218 const struct timespec *tv2)
1220 return (tv1->tv_sec < tv2->tv_sec)
1222 (tv1->tv_sec == tv2->tv_sec && tv1->tv_nsec < tv2->tv_nsec);
1226 /* threads_current_time_is_earlier_than ****************************************
1228 Check if the current time is earlier than the given timespec.
1231 tv...........the timespec to compare against
1234 true, if the current time is earlier
1236 *******************************************************************************/
1238 static bool threads_current_time_is_earlier_than(const struct timespec *tv)
1240 struct timeval tvnow;
1241 struct timespec tsnow;
1243 /* get current time */
1245 if (gettimeofday(&tvnow, NULL) != 0)
1246 vm_abort("gettimeofday failed: %s\n", strerror(errno));
1248 /* convert it to a timespec */
1250 tsnow.tv_sec = tvnow.tv_sec;
1251 tsnow.tv_nsec = tvnow.tv_usec * 1000;
1253 /* compare current time with the given timespec */
1255 return threads_timespec_earlier(&tsnow, tv);
1259 /* threads_wait_with_timeout ***************************************************
1261 Wait until the given point in time on a monitor until either
1262 we are notified, we are interrupted, or the time is up.
1265 t............the current thread
1266 wakeupTime...absolute (latest) wakeup time
1267 If both tv_sec and tv_nsec are zero, this function
1268 waits for an unlimited amount of time.
1270 *******************************************************************************/
1272 static void threads_wait_with_timeout(threadobject *t, struct timespec *wakeupTime, bool parking)
1274 // Acquire the waitmutex.
1275 t->waitmutex->lock();
1277 /* wait on waitcond */
1279 if (wakeupTime->tv_sec || wakeupTime->tv_nsec) {
1281 while (!t->interrupted && !(parking ? t->park_permit : t->signaled)
1282 && threads_current_time_is_earlier_than(wakeupTime))
1285 thread_set_state_timed_parked(t);
1287 thread_set_state_timed_waiting(t);
1289 t->waitcond->timedwait(t->waitmutex, wakeupTime);
1291 thread_set_state_runnable(t);
1296 while (!t->interrupted && !(parking ? t->park_permit : t->signaled)) {
1298 thread_set_state_parked(t);
1300 thread_set_state_waiting(t);
1302 t->waitcond->wait(t->waitmutex);
1304 thread_set_state_runnable(t);
1309 t->park_permit = false;
1311 // Release the waitmutex.
1312 t->waitmutex->unlock();
1316 /* threads_wait_with_timeout_relative ******************************************
1318 Wait for the given maximum amount of time on a monitor until either
1319 we are notified, we are interrupted, or the time is up.
1322 t............the current thread
1323 millis.......milliseconds to wait
1324 nanos........nanoseconds to wait
1326 *******************************************************************************/
1328 void threads_wait_with_timeout_relative(threadobject *thread, s8 millis,
1331 struct timespec wakeupTime;
1333 /* calculate the the (latest) wakeup time */
1335 threads_calc_absolute_time(&wakeupTime, millis, nanos);
1339 threads_wait_with_timeout(thread, &wakeupTime, false);
1343 /* threads_calc_absolute_time **************************************************
1345 Calculate the absolute point in time a given number of ms and ns from now.
1348 millis............milliseconds from now
1349 nanos.............nanoseconds from now
1352 *tm...............receives the timespec of the absolute point in time
1354 *******************************************************************************/
1356 static void threads_calc_absolute_time(struct timespec *tm, s8 millis, s4 nanos)
1358 // (at least with GNU classpath) we know that 0 <= nanos <= 999999
1360 if (!millis && !nanos)
1363 gettimeofday(&tv, NULL);
1364 s8 secs = tv.tv_sec + millis / 1000;
1365 if (secs > INT32_MAX) // integer overflow
1369 long nsec = tv.tv_usec * 1000 + (s4) millis * 1000000 + nanos;
1370 tm->tv_sec = tv.tv_sec + nsec / 1000000000;
1371 if (tm->tv_sec < tv.tv_sec) // integer overflow
1373 tm->tv_nsec = nsec % 1000000000;
1381 /* threads_thread_interrupt ****************************************************
1383 Interrupt the given thread.
1385 The thread gets the "waitcond" signal and
1386 its interrupted flag is set to true.
1389 thread............the thread to interrupt
1391 *******************************************************************************/
1393 void threads_thread_interrupt(threadobject *t)
1395 /* Signal the thread a "waitcond" and tell it that it has been
1398 t->waitmutex->lock();
1400 DEBUGTHREADS("interrupted", t);
1402 /* Interrupt blocking system call using a signal. */
1404 pthread_kill(t->tid, Signal_INTERRUPT_SYSTEM_CALL);
1406 t->waitcond->signal();
1408 t->interrupted = true;
1410 t->waitmutex->unlock();
1415 * Sleep the current thread for the specified amount of time.
1417 * @param millis Milliseconds to sleep.
1418 * @param nanos Nanoseconds to sleep.
1420 void threads_sleep(int64_t millis, int32_t nanos)
1423 struct timespec wakeupTime;
1427 /* exceptions_throw_illegalargumentexception("timeout value is negative"); */
1428 exceptions_throw_illegalargumentexception();
1432 t = thread_get_current();
1434 if (thread_is_interrupted(t) && !exceptions_get_exception()) {
1435 /* Clear interrupted flag (Mauve test:
1436 gnu/testlet/java/lang/Thread/interrupt). */
1438 thread_set_interrupted(t, false);
1440 /* exceptions_throw_interruptedexception("sleep interrupted"); */
1441 exceptions_throw_interruptedexception();
1445 // (Note taken from classpath/vm/reference/java/lang/VMThread.java (sleep))
1446 // Note: JDK treats a zero length sleep is like Thread.yield(),
1447 // without checking the interrupted status of the thread. It's
1448 // unclear if this is a bug in the implementation or the spec.
1449 // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6213203 */
1450 if (millis == 0 && nanos == 0) {
1454 threads_calc_absolute_time(&wakeupTime, millis, nanos);
1456 threads_wait_with_timeout(t, &wakeupTime, false);
1458 interrupted = thread_is_interrupted(t);
1461 thread_set_interrupted(t, false);
1463 // An other exception could have been thrown
1464 // (e.g. ThreadDeathException).
1465 if (!exceptions_get_exception())
1466 exceptions_throw_interruptedexception();
1472 * Park the current thread for the specified amount of time or until a
1473 * specified deadline.
1475 * @param absolute Is the time in nanos a deadline or a duration?
1476 * @param nanos Nanoseconds to park (absolute=false)
1477 * or deadline in milliseconds (absolute=true)
1479 void threads_park(bool absolute, int64_t nanos)
1482 struct timespec wakeupTime;
1484 t = thread_get_current();
1487 wakeupTime.tv_nsec = 0;
1488 wakeupTime.tv_sec = nanos / 1000; /* milliseconds */
1491 threads_calc_absolute_time(&wakeupTime, nanos / 1000000, nanos % 1000000);
1493 threads_wait_with_timeout(t, &wakeupTime, true);
1497 * Unpark the specified thread.
1499 * @param t The thread to unpark.
1501 void threads_unpark(threadobject *t)
1503 t->waitmutex->lock();
1505 t->waitcond->signal();
1507 t->park_permit = true;
1509 t->waitmutex->unlock();
1513 /* threads_yield ***************************************************************
1515 Yield to the scheduler.
1517 *******************************************************************************/
1519 void threads_yield(void)
1524 #if defined(ENABLE_TLH)
1526 void threads_tlh_add_frame() {
1527 tlh_add_frame(&(THREADOBJECT->tlh));
1530 void threads_tlh_remove_frame() {
1531 tlh_remove_frame(&(THREADOBJECT->tlh));
1538 * These are local overrides for various environment variables in Emacs.
1539 * Please do not remove this and leave it at the end of the file, where
1540 * Emacs will automagically detect them.
1541 * ---------------------------------------------------------------------
1544 * indent-tabs-mode: t
1548 * vim:noexpandtab:sw=4:ts=4: