1 /* src/threads/posix/thread-posix.cpp - POSIX thread functions
3 Copyright (C) 1996-2005, 2006, 2007, 2008
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 */
33 #include <sys/types.h>
46 #include "mm/memory.h"
48 #if defined(ENABLE_GC_CACAO)
49 # include "mm/cacao-gc/gc.h"
52 #include "native/llni.h"
53 #include "native/native.h"
55 #include "threads/condition.hpp"
56 #include "threads/lock-common.h"
57 #include "threads/mutex.hpp"
58 #include "threads/threadlist.h"
59 #include "threads/thread.hpp"
61 #include "toolbox/logging.h"
63 #include "vm/builtin.h"
64 #include "vm/exceptions.hpp"
65 #include "vm/global.h"
66 #include "vm/globals.hpp"
67 #include "vm/javaobjects.hpp"
68 #include "vm/options.h"
69 #include "vm/signallocal.h"
70 #include "vm/string.hpp"
73 #if defined(ENABLE_STATISTICS)
74 # include "vm/statistics.h"
77 #include "vm/jit/asmpart.h"
79 #if !defined(__DARWIN__)
80 # include <semaphore.h>
83 #if defined(__LINUX__)
84 # define GC_LINUX_THREADS
85 #elif defined(__IRIX__)
86 # define GC_IRIX_THREADS
87 #elif defined(__DARWIN__)
88 # define GC_DARWIN_THREADS
91 #if defined(ENABLE_GC_BOEHM)
92 /* We need to include Boehm's gc.h here because it overrides
93 pthread_create and friends. */
94 # include "mm/boehm-gc/include/gc.h"
97 #if defined(ENABLE_JVMTI)
98 #include "native/jvmti/cacaodbg.h"
102 // FIXME For now we export everything as C functions.
105 #if defined(__DARWIN__)
106 /* Darwin has no working semaphore implementation. This one is taken
110 This is a very simple semaphore implementation for Darwin. It
111 is implemented in terms of pthreads calls so it isn't async signal
112 safe. This isn't a problem because signals aren't used to
113 suspend threads on Darwin.
116 static int sem_init(sem_t *sem, int pshared, int value)
121 sem->mutex = new Mutex();
122 sem->cond = new Condition();
128 static int sem_post(sem_t *sem)
133 sem->mutex->unlock();
138 static int sem_wait(sem_t *sem)
142 while (sem->value == 0) {
143 sem->cond->wait(sem->mutex);
147 sem->mutex->unlock();
152 static int sem_destroy(sem_t *sem)
159 #endif /* defined(__DARWIN__) */
162 /* startupinfo *****************************************************************
164 Struct used to pass info from threads_start_thread to
165 threads_startup_thread.
167 ******************************************************************************/
170 threadobject *thread; /* threadobject for this thread */
171 functionptr function; /* function to run in the new thread */
172 sem_t *psem; /* signals when thread has been entered */
173 /* in the thread list */
174 sem_t *psem_first; /* signals when pthread_create has returned */
178 /* prototypes *****************************************************************/
180 static void threads_calc_absolute_time(struct timespec *tm, s8 millis, s4 nanos);
183 /******************************************************************************/
184 /* GLOBAL VARIABLES */
185 /******************************************************************************/
187 /* the thread object of the current thread */
188 /* This is either a thread-local variable defined with __thread, or */
189 /* a thread-specific value stored with key threads_current_threadobject_key. */
190 #if defined(HAVE___THREAD)
191 __thread threadobject *thread_current;
193 pthread_key_t thread_current_key;
196 /* global mutex for stop-the-world */
197 static Mutex* stopworldlock;
199 #if defined(ENABLE_GC_CACAO)
200 /* global mutex for the GC */
201 static Mutex* mutex_gc;
204 /* global mutex and condition for joining threads on exit */
205 static Mutex* mutex_join;
206 static Condition* cond_join;
208 #if defined(ENABLE_GC_CACAO)
209 /* semaphore used for acknowleding thread suspension */
210 static sem_t suspend_ack;
214 /* threads_sem_init ************************************************************
216 Initialize a semaphore. Checks against errors and interruptions.
219 sem..............the semaphore to initialize
220 shared...........true if this semaphore will be shared between processes
221 value............the initial value for the semaphore
223 *******************************************************************************/
225 void threads_sem_init(sem_t *sem, bool shared, int value)
232 r = sem_init(sem, shared, value);
235 } while (errno == EINTR);
237 vm_abort("sem_init failed: %s", strerror(errno));
241 /* threads_sem_wait ************************************************************
243 Wait for a semaphore, non-interruptible.
245 IMPORTANT: Always use this function instead of `sem_wait` directly, as
246 `sem_wait` may be interrupted by signals!
249 sem..............the semaphore to wait on
251 *******************************************************************************/
253 void threads_sem_wait(sem_t *sem)
263 } while (errno == EINTR);
265 vm_abort("sem_wait failed: %s", strerror(errno));
269 /* threads_sem_post ************************************************************
271 Increase the count of a semaphore. Checks for errors.
274 sem..............the semaphore to increase the count of
276 *******************************************************************************/
278 void threads_sem_post(sem_t *sem)
284 /* unlike sem_wait, sem_post is not interruptible */
290 vm_abort("sem_post failed: %s", strerror(errno));
294 /* threads_stopworld ***********************************************************
296 Stops the world from turning. All threads except the calling one
297 are suspended. The function returns as soon as all threads have
298 acknowledged their suspension.
300 *******************************************************************************/
302 #if defined(ENABLE_GC_CACAO)
303 void threads_stopworld(void)
305 #if !defined(__DARWIN__) && !defined(__CYGWIN__)
312 stopworldlock->lock();
314 /* lock the threads lists */
318 #if defined(__DARWIN__)
319 /*threads_cast_darwinstop();*/
321 #elif defined(__CYGWIN__)
327 DEBUGTHREADS("stops World", self);
331 /* suspend all running threads */
332 for (t = threadlist_first(); t != NULL; t = threadlist_next(t)) {
333 /* don't send the signal to ourself */
338 /* don't send the signal to NEW threads (because they are not
339 completely initialized) */
341 if (t->state == THREAD_STATE_NEW)
344 /* send the signal */
346 result = threads_suspend_thread(t, SUSPEND_REASON_STOPWORLD);
349 /* increase threads count */
354 /* wait for all threads signaled to suspend */
355 for (i = 0; i < count; i++)
356 threads_sem_wait(&suspend_ack);
359 /* ATTENTION: Don't unlock the threads-lists here so that
360 non-signaled NEW threads can't change their state and execute
366 /* threads_startworld **********************************************************
368 Starts the world again after it has previously been stopped.
370 *******************************************************************************/
372 #if defined(ENABLE_GC_CACAO)
373 void threads_startworld(void)
375 #if !defined(__DARWIN__) && !defined(__CYGWIN__)
382 #if defined(__DARWIN__)
383 /*threads_cast_darwinresume();*/
385 #elif defined(__IRIX__)
386 threads_cast_irixresume();
387 #elif defined(__CYGWIN__)
393 DEBUGTHREADS("starts World", self);
397 /* resume all thread we haltet */
398 for (t = threadlist_first(); t != NULL; t = threadlist_next(t)) {
399 /* don't send the signal to ourself */
404 /* don't send the signal to NEW threads (because they are not
405 completely initialized) */
407 if (t->state == THREAD_STATE_NEW)
410 /* send the signal */
412 result = threads_resume_thread(t);
415 /* increase threads count */
420 /* wait for all threads signaled to suspend */
421 for (i = 0; i < count; i++)
422 threads_sem_wait(&suspend_ack);
426 /* unlock the threads lists */
430 stopworldlock->unlock();
435 /* threads_impl_thread_init ****************************************************
437 Initialize OS-level locking constructs in threadobject.
440 t....the threadobject
442 *******************************************************************************/
444 void threads_impl_thread_init(threadobject *t)
446 /* initialize the mutex and the condition */
448 t->flc_lock = new Mutex();
449 t->flc_cond = new Condition();
451 t->waitmutex = new Mutex();
452 t->waitcond = new Condition();
454 t->suspendmutex = new Mutex();
455 t->suspendcond = new Condition();
457 #if defined(ENABLE_TLH)
462 /* threads_impl_thread_clear ***************************************************
464 Clears all fields in threadobject the way an MZERO would have
465 done. MZERO cannot be used anymore because it would mess up the
469 t....the threadobject
471 *******************************************************************************/
473 void threads_impl_thread_clear(threadobject *t)
485 #if defined(__DARWIN__)
489 t->interrupted = false;
492 t->suspended = false;
493 t->suspend_reason = 0;
497 t->_exceptionptr = NULL;
498 t->_stackframeinfo = NULL;
499 t->_localref_table = NULL;
501 #if defined(ENABLE_INTRP)
502 t->_global_sp = NULL;
505 #if defined(ENABLE_GC_CACAO)
506 t->gc_critical = false;
512 MZERO(&t->dumpinfo, dumpinfo_t, 1);
515 /* threads_impl_thread_reuse ***************************************************
517 Resets some implementation fields in threadobject. This was
518 previously done in threads_impl_thread_new.
521 t....the threadobject
523 *******************************************************************************/
525 void threads_impl_thread_reuse(threadobject *t)
527 /* get the pthread id */
529 t->tid = pthread_self();
531 #if defined(ENABLE_DEBUG_FILTER)
532 /* Initialize filter counters */
533 t->filterverbosecallctr[0] = 0;
534 t->filterverbosecallctr[1] = 0;
538 t->tracejavacallindent = 0;
539 t->tracejavacallcount = 0;
546 /* not really needed */
547 t->flc_object = NULL;
549 #if defined(ENABLE_TLH)
550 tlh_destroy(&(t->tlh));
556 /* threads_impl_thread_free ****************************************************
558 Cleanup thread stuff.
561 t....the threadobject
563 *******************************************************************************/
567 void threads_impl_thread_free(threadobject *t)
571 /* Destroy the mutex and the condition. */
575 result = pthread_cond_destroy(&(t->flc_cond));
578 vm_abort_errnum(result, "threads_impl_thread_free: pthread_cond_destroy failed");
582 result = pthread_cond_destroy(&(t->waitcond));
585 vm_abort_errnum(result, "threads_impl_thread_free: pthread_cond_destroy failed");
587 delete t->suspendmutex;
589 result = pthread_cond_destroy(&(t->suspendcond));
592 vm_abort_errnum(result, "threads_impl_thread_free: pthread_cond_destroy failed");
597 /* threads_impl_preinit ********************************************************
599 Do some early initialization of stuff required.
601 ATTENTION: Do NOT use any Java heap allocation here, as gc_init()
602 is called AFTER this function!
604 *******************************************************************************/
606 void threads_impl_preinit(void)
610 stopworldlock = new Mutex();
612 /* initialize exit mutex and condition (on exit we join all
615 mutex_join = new Mutex();
616 cond_join = new Condition();
618 #if defined(ENABLE_GC_CACAO)
619 /* initialize the GC mutex & suspend semaphore */
621 mutex_gc = new Mutex();
622 threads_sem_init(&suspend_ack, 0, 0);
625 #if !defined(HAVE___THREAD)
626 result = pthread_key_create(&thread_current_key, NULL);
628 vm_abort_errnum(result, "threads_impl_preinit: pthread_key_create failed");
633 /* threads_mutex_gc_lock *******************************************************
635 Enter the global GC mutex.
637 *******************************************************************************/
639 #if defined(ENABLE_GC_CACAO)
640 void threads_mutex_gc_lock(void)
647 /* threads_mutex_gc_unlock *****************************************************
649 Leave the global GC mutex.
651 *******************************************************************************/
653 #if defined(ENABLE_GC_CACAO)
654 void threads_mutex_gc_unlock(void)
660 /* threads_mutex_join_lock *****************************************************
662 Enter the join mutex.
664 *******************************************************************************/
666 void threads_mutex_join_lock(void)
672 /* threads_mutex_join_unlock ***************************************************
674 Leave the join mutex.
676 *******************************************************************************/
678 void threads_mutex_join_unlock(void)
680 mutex_join->unlock();
684 /* threads_impl_init ***********************************************************
686 Initializes the implementation specific bits.
688 *******************************************************************************/
690 void threads_impl_init(void)
695 threads_set_thread_priority(pthread_self(), NORM_PRIORITY);
697 /* Initialize the thread attribute object. */
699 result = pthread_attr_init(&attr);
702 vm_abort_errnum(result, "threads_impl_init: pthread_attr_init failed");
704 result = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
707 vm_abort_errnum(result, "threads_impl_init: pthread_attr_setdetachstate failed");
711 /* threads_startup_thread ******************************************************
713 Thread startup function called by pthread_create.
715 Thread which have a startup.function != NULL are marked as internal
716 threads. All other threads are threated as normal Java threads.
718 NOTE: This function is not called directly by pthread_create. The Boehm GC
719 inserts its own GC_start_routine in between, which then calls
723 arg..........the argument passed to pthread_create, ie. a pointer to
724 a startupinfo struct. CAUTION: When the `psem` semaphore
725 is posted, the startupinfo struct becomes invalid! (It
726 is allocated on the stack of threads_start_thread.)
728 ******************************************************************************/
730 static void *threads_startup_thread(void *arg)
732 startupinfo *startup;
737 functionptr function;
739 #if defined(ENABLE_GC_BOEHM)
740 # if !defined(__DARWIN__)
741 struct GC_stack_base sb;
746 #if defined(ENABLE_INTRP)
747 u1 *intrp_thread_stack;
750 #if defined(ENABLE_INTRP)
751 /* create interpreter stack */
754 intrp_thread_stack = GCMNEW(u1, opt_stacksize);
755 MSET(intrp_thread_stack, 0, u1, opt_stacksize);
758 intrp_thread_stack = NULL;
761 /* get passed startupinfo structure and the values in there */
763 startup = (startupinfo*) arg;
766 function = startup->function;
767 psem = startup->psem;
769 /* Seems like we've encountered a situation where thread->tid was
770 not set by pthread_create. We alleviate this problem by waiting
771 for pthread_create to return. */
773 threads_sem_wait(startup->psem_first);
775 #if defined(__DARWIN__)
776 t->mach_thread = mach_thread_self();
779 /* Now that we are in the new thread, we can store the internal
780 thread data-structure in the TSD. */
782 thread_set_current(t);
784 #if defined(ENABLE_GC_BOEHM)
785 # if defined(__DARWIN__)
786 // This is currently not implemented in Boehm-GC. Just fail silently.
788 /* Register the thread with Boehm-GC. This must happen before the
789 thread allocates any memory from the GC heap.*/
791 result = GC_get_stack_base(&sb);
794 vm_abort("threads_startup_thread: GC_get_stack_base failed: result=%d", result);
796 GC_register_my_thread(&sb);
800 // Get the java.lang.Thread object for this thread.
801 java_handle_t* object = thread_get_object(t);
802 java_lang_Thread jlt(object);
804 /* set our priority */
806 threads_set_thread_priority(t->tid, jlt.get_priority());
808 /* Thread is completely initialized. */
810 thread_set_state_runnable(t);
812 /* tell threads_startup_thread that we registered ourselves */
813 /* CAUTION: *startup becomes invalid with this! */
816 threads_sem_post(psem);
818 #if defined(ENABLE_INTRP)
819 /* set interpreter stack */
822 thread->_global_sp = (Cell *) (intrp_thread_stack + opt_stacksize);
825 #if defined(ENABLE_JVMTI)
826 /* fire thread start event */
829 jvmti_ThreadStartEnd(JVMTI_EVENT_THREAD_START);
832 DEBUGTHREADS("starting", t);
834 /* find and run the Thread.run()V method if no other function was passed */
836 if (function == NULL) {
837 #if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
838 /* We need to start the run method of
839 java.lang.VMThread. Since this is a final class, we can use
840 the class object directly. */
842 c = class_java_lang_VMThread;
843 #elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK) || defined(WITH_JAVA_RUNTIME_LIBRARY_CLDC1_1)
844 LLNI_class_get(object, c);
846 # error unknown classpath configuration
849 m = class_resolveclassmethod(c, utf_run, utf_void__void, c, true);
852 vm_abort("threads_startup_thread: run() method not found in class");
854 /* set ThreadMXBean variables */
856 /* _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount++; */
857 /* _Jv_jvm->java_lang_management_ThreadMXBean_TotalStartedThreadCount++; */
859 /* if (_Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount > */
860 /* _Jv_jvm->java_lang_management_ThreadMXBean_PeakThreadCount) */
861 /* _Jv_jvm->java_lang_management_ThreadMXBean_PeakThreadCount = */
862 /* _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount; */
865 #if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
867 // We need to start the run method of java.lang.VMThread.
868 java_lang_VMThread jlvmt(jlt.get_vmThread());
869 java_handle_t* h = jlvmt.get_handle();
871 #elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK) || defined(WITH_JAVA_RUNTIME_LIBRARY_CLDC1_1)
873 java_handle_t* h = jlt.get_handle();
876 # error unknown classpath configuration
879 /* Run the thread. */
881 (void) vm_call_method(m, h);
884 /* set ThreadMXBean variables */
886 /* _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount++; */
887 /* _Jv_jvm->java_lang_management_ThreadMXBean_TotalStartedThreadCount++; */
889 /* if (_Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount > */
890 /* _Jv_jvm->java_lang_management_ThreadMXBean_PeakThreadCount) */
891 /* _Jv_jvm->java_lang_management_ThreadMXBean_PeakThreadCount = */
892 /* _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount; */
895 /* call passed function, e.g. finalizer_thread */
900 DEBUGTHREADS("stopping", t);
902 #if defined(ENABLE_JVMTI)
903 /* fire thread end event */
906 jvmti_ThreadStartEnd(JVMTI_EVENT_THREAD_END);
909 /* We ignore the return value. */
911 (void) thread_detach_current_thread();
913 /* set ThreadMXBean variables */
915 /* _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount--; */
922 /* threads_impl_thread_start ***************************************************
924 Start a thread in the JVM. Both (vm internal and java) thread
928 thread....the thread object
929 f.........function to run in the new thread. NULL means that the
930 "run" method of the object `t` should be called
932 ******************************************************************************/
934 void threads_impl_thread_start(threadobject *thread, functionptr f)
942 /* fill startupinfo structure passed by pthread_create to
943 * threads_startup_thread */
945 startup.thread = thread;
946 startup.function = f; /* maybe we don't call Thread.run()V */
948 startup.psem_first = &sem_first;
950 threads_sem_init(&sem, 0, 0);
951 threads_sem_init(&sem_first, 0, 0);
953 /* Initialize thread attributes. */
955 result = pthread_attr_init(&attr);
958 vm_abort_errnum(result, "threads_impl_thread_start: pthread_attr_init failed");
960 result = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
963 vm_abort_errnum(result, "threads_impl_thread_start: pthread_attr_setdetachstate failed");
965 /* initialize thread stacksize */
967 result = pthread_attr_setstacksize(&attr, opt_stacksize);
970 vm_abort_errnum(result, "threads_impl_thread_start: pthread_attr_setstacksize failed");
972 /* create the thread */
974 result = pthread_create(&(thread->tid), &attr, threads_startup_thread, &startup);
977 vm_abort_errnum(result, "threads_impl_thread_start: pthread_create failed");
979 /* destroy the thread attributes */
981 result = pthread_attr_destroy(&attr);
984 vm_abort_errnum(result, "threads_impl_thread_start: pthread_attr_destroy failed");
986 /* signal that pthread_create has returned, so thread->tid is valid */
988 threads_sem_post(&sem_first);
990 /* wait here until the thread has entered itself into the thread list */
992 threads_sem_wait(&sem);
997 sem_destroy(&sem_first);
1001 /* threads_set_thread_priority *************************************************
1003 Set the priority of the given thread.
1006 tid..........thread id
1007 priority.....priority to set
1009 ******************************************************************************/
1011 void threads_set_thread_priority(pthread_t tid, int priority)
1013 struct sched_param schedp;
1016 pthread_getschedparam(tid, &policy, &schedp);
1017 schedp.sched_priority = priority;
1018 pthread_setschedparam(tid, policy, &schedp);
1023 * Detaches the current thread from the VM.
1025 * @return true on success, false otherwise
1027 bool thread_detach_current_thread(void)
1029 threadobject* t = thread_get_current();
1035 /* If the given thread has already been detached, this operation
1038 if (thread_is_attached(t) == false)
1041 DEBUGTHREADS("detaching", t);
1043 java_handle_t* object = thread_get_object(t);
1044 java_lang_Thread jlt(object);
1046 #if defined(ENABLE_JAVASE)
1047 java_handle_t* group = jlt.get_group();
1049 /* If there's an uncaught exception, call uncaughtException on the
1050 thread's exception handler, or the thread's group if this is
1053 java_handle_t* e = exceptions_get_and_clear_exception();
1056 /* We use the type void* for handler here, as it's not trivial
1057 to build the java_lang_Thread_UncaughtExceptionHandler
1058 header file with cacaoh. */
1060 # if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
1062 java_handle_t* handler = jlt.get_exceptionHandler();
1064 # elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK)
1066 java_handle_t* handler = jlt.get_uncaughtExceptionHandler();
1073 if (handler != NULL) {
1074 LLNI_class_get(handler, c);
1075 h = (java_handle_t *) handler;
1078 LLNI_class_get(group, c);
1079 h = (java_handle_t *) group;
1082 methodinfo* m = class_resolveclassmethod(c,
1083 utf_uncaughtException,
1084 utf_java_lang_Thread_java_lang_Throwable__V,
1091 (void) vm_call_method(m, h, object, e);
1093 if (exceptions_get_exception())
1097 /* XXX TWISTI: should all threads be in a ThreadGroup? */
1099 /* Remove thread from the thread group. */
1101 if (group != NULL) {
1103 LLNI_class_get(group, c);
1105 # if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
1106 methodinfo* m = class_resolveclassmethod(c,
1108 utf_java_lang_Thread__V,
1109 class_java_lang_ThreadGroup,
1111 # elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK)
1112 methodinfo* m = class_resolveclassmethod(c,
1114 utf_java_lang_Thread__V,
1115 class_java_lang_ThreadGroup,
1118 # error unknown classpath configuration
1124 (void) vm_call_method(m, group, object);
1126 if (exceptions_get_exception())
1129 // Clear the ThreadGroup in the Java thread object (Mauve
1130 // test: gnu/testlet/java/lang/Thread/getThreadGroup).
1131 jlt.set_group(NULL);
1135 /* Thread has terminated. */
1137 thread_set_state_terminated(t);
1139 /* Notify all threads waiting on this thread. These are joining
1142 /* XXX Care about exceptions? */
1143 (void) lock_monitor_enter(jlt.get_handle());
1145 lock_notify_all_object(jlt.get_handle());
1147 /* XXX Care about exceptions? */
1148 (void) lock_monitor_exit(jlt.get_handle());
1150 /* Enter the join-mutex before calling thread_free, so
1151 threads_join_all_threads gets the correct number of non-daemon
1154 threads_mutex_join_lock();
1156 /* Free the internal thread data-structure. */
1160 /* Signal that this thread has finished and leave the mutex. */
1162 cond_join->signal();
1163 threads_mutex_join_unlock();
1169 /* threads_suspend_thread ******************************************************
1171 Suspend the passed thread. Execution stops until the thread
1172 is explicitly resumend again.
1175 reason.....Reason for suspending this thread.
1177 *******************************************************************************/
1179 bool threads_suspend_thread(threadobject *thread, s4 reason)
1181 /* acquire the suspendmutex */
1182 thread->suspendmutex->lock();
1184 if (thread->suspended) {
1185 thread->suspendmutex->unlock();
1189 /* set the reason for the suspension */
1190 thread->suspend_reason = reason;
1192 /* send the suspend signal to the thread */
1193 assert(thread != THREADOBJECT);
1194 if (pthread_kill(thread->tid, SIGUSR1) != 0)
1195 vm_abort("threads_suspend_thread: pthread_kill failed: %s",
1198 /* REMEMBER: do not release the suspendmutex, this is done
1199 by the thread itself in threads_suspend_ack(). */
1205 /* threads_suspend_ack *********************************************************
1207 Acknowledges the suspension of the current thread.
1210 pc.....The PC where the thread suspended its execution.
1211 sp.....The SP before the thread suspended its execution.
1213 *******************************************************************************/
1215 #if defined(ENABLE_GC_CACAO)
1216 void threads_suspend_ack(u1* pc, u1* sp)
1218 threadobject *thread;
1220 thread = THREADOBJECT;
1222 assert(thread->suspend_reason != 0);
1224 /* TODO: remember dump memory size */
1226 /* inform the GC about the suspension */
1227 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD && gc_pending) {
1229 /* check if the GC wants to leave the thread running */
1230 if (!gc_suspend(thread, pc, sp)) {
1232 /* REMEMBER: we do not unlock the suspendmutex because the thread
1233 will suspend itself again at a later time */
1239 /* mark this thread as suspended and remember the PC */
1241 thread->suspended = true;
1243 /* if we are stopping the world, we should send a global ack */
1244 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD) {
1245 threads_sem_post(&suspend_ack);
1248 DEBUGTHREADS("suspending", thread);
1250 /* release the suspension mutex and wait till we are resumed */
1251 thread->suspendcond->wait(thread->suspendmutex);
1253 DEBUGTHREADS("resuming", thread);
1255 /* if we are stopping the world, we should send a global ack */
1256 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD) {
1257 threads_sem_post(&suspend_ack);
1260 /* TODO: free dump memory */
1262 /* release the suspendmutex */
1263 thread->suspendmutex->unlock();
1268 /* threads_resume_thread *******************************************************
1270 Resumes the execution of the passed thread.
1272 *******************************************************************************/
1274 #if defined(ENABLE_GC_CACAO)
1275 bool threads_resume_thread(threadobject *thread)
1277 /* acquire the suspendmutex */
1278 thread->suspendmutex->lock();
1280 if (!thread->suspended) {
1281 thread->suspendmutex->unlock();
1285 thread->suspended = false;
1287 /* tell everyone that the thread should resume */
1288 assert(thread != THREADOBJECT);
1289 thread->suspendcond->broadcast();
1291 /* release the suspendmutex */
1292 thread->suspendmutex->unlock();
1299 /* threads_join_all_threads ****************************************************
1301 Join all non-daemon threads.
1303 *******************************************************************************/
1305 void threads_join_all_threads(void)
1309 /* get current thread */
1313 /* This thread is waiting for all non-daemon threads to exit. */
1315 thread_set_state_waiting(t);
1317 /* enter join mutex */
1319 threads_mutex_join_lock();
1321 /* Wait for condition as long as we have non-daemon threads. We
1322 compare against 1 because the current (main thread) is also a
1323 non-daemon thread. */
1325 while (threadlist_get_non_daemons() > 1)
1326 cond_join->wait(mutex_join);
1328 /* leave join mutex */
1330 threads_mutex_join_unlock();
1334 /* threads_timespec_earlier ****************************************************
1336 Return true if timespec tv1 is earlier than timespec tv2.
1339 tv1..........first timespec
1340 tv2..........second timespec
1343 true, if the first timespec is earlier
1345 *******************************************************************************/
1347 static inline bool threads_timespec_earlier(const struct timespec *tv1,
1348 const struct timespec *tv2)
1350 return (tv1->tv_sec < tv2->tv_sec)
1352 (tv1->tv_sec == tv2->tv_sec && tv1->tv_nsec < tv2->tv_nsec);
1356 /* threads_current_time_is_earlier_than ****************************************
1358 Check if the current time is earlier than the given timespec.
1361 tv...........the timespec to compare against
1364 true, if the current time is earlier
1366 *******************************************************************************/
1368 static bool threads_current_time_is_earlier_than(const struct timespec *tv)
1370 struct timeval tvnow;
1371 struct timespec tsnow;
1373 /* get current time */
1375 if (gettimeofday(&tvnow, NULL) != 0)
1376 vm_abort("gettimeofday failed: %s\n", strerror(errno));
1378 /* convert it to a timespec */
1380 tsnow.tv_sec = tvnow.tv_sec;
1381 tsnow.tv_nsec = tvnow.tv_usec * 1000;
1383 /* compare current time with the given timespec */
1385 return threads_timespec_earlier(&tsnow, tv);
1389 /* threads_wait_with_timeout ***************************************************
1391 Wait until the given point in time on a monitor until either
1392 we are notified, we are interrupted, or the time is up.
1395 t............the current thread
1396 wakeupTime...absolute (latest) wakeup time
1397 If both tv_sec and tv_nsec are zero, this function
1398 waits for an unlimited amount of time.
1400 *******************************************************************************/
1402 static void threads_wait_with_timeout(threadobject *t, struct timespec *wakeupTime)
1404 // Acquire the waitmutex.
1405 t->waitmutex->lock();
1407 /* wait on waitcond */
1409 if (wakeupTime->tv_sec || wakeupTime->tv_nsec) {
1411 while (!t->interrupted && !t->signaled
1412 && threads_current_time_is_earlier_than(wakeupTime))
1414 thread_set_state_timed_waiting(t);
1416 t->waitcond->timedwait(t->waitmutex, wakeupTime);
1418 thread_set_state_runnable(t);
1423 while (!t->interrupted && !t->signaled) {
1424 thread_set_state_waiting(t);
1426 t->waitcond->wait(t->waitmutex);
1428 thread_set_state_runnable(t);
1432 // Release the waitmutex.
1433 t->waitmutex->unlock();
1437 /* threads_wait_with_timeout_relative ******************************************
1439 Wait for the given maximum amount of time on a monitor until either
1440 we are notified, we are interrupted, or the time is up.
1443 t............the current thread
1444 millis.......milliseconds to wait
1445 nanos........nanoseconds to wait
1447 *******************************************************************************/
1449 void threads_wait_with_timeout_relative(threadobject *thread, s8 millis,
1452 struct timespec wakeupTime;
1454 /* calculate the the (latest) wakeup time */
1456 threads_calc_absolute_time(&wakeupTime, millis, nanos);
1460 threads_wait_with_timeout(thread, &wakeupTime);
1464 /* threads_calc_absolute_time **************************************************
1466 Calculate the absolute point in time a given number of ms and ns from now.
1469 millis............milliseconds from now
1470 nanos.............nanoseconds from now
1473 *tm...............receives the timespec of the absolute point in time
1475 *******************************************************************************/
1477 static void threads_calc_absolute_time(struct timespec *tm, s8 millis, s4 nanos)
1479 if ((millis != 0x7fffffffffffffffLLU) && (millis || nanos)) {
1482 gettimeofday(&tv, NULL);
1483 tv.tv_sec += millis / 1000;
1485 nsec = tv.tv_usec * 1000 + (s4) millis * 1000000 + nanos;
1486 tm->tv_sec = tv.tv_sec + nsec / 1000000000;
1487 tm->tv_nsec = nsec % 1000000000;
1496 /* threads_thread_interrupt ****************************************************
1498 Interrupt the given thread.
1500 The thread gets the "waitcond" signal and
1501 its interrupted flag is set to true.
1504 thread............the thread to interrupt
1506 *******************************************************************************/
1508 void threads_thread_interrupt(threadobject *t)
1510 /* Signal the thread a "waitcond" and tell it that it has been
1513 t->waitmutex->lock();
1515 DEBUGTHREADS("interrupted", t);
1517 /* Interrupt blocking system call using a signal. */
1519 pthread_kill(t->tid, Signal_INTERRUPT_SYSTEM_CALL);
1521 t->waitcond->signal();
1523 t->interrupted = true;
1525 t->waitmutex->unlock();
1530 * Sleep the current thread for the specified amount of time.
1532 * @param millis Milliseconds to sleep.
1533 * @param nanos Nanoseconds to sleep.
1535 void threads_sleep(int64_t millis, int32_t nanos)
1538 struct timespec wakeupTime;
1542 /* exceptions_throw_illegalargumentexception("timeout value is negative"); */
1543 exceptions_throw_illegalargumentexception();
1547 t = thread_get_current();
1549 if (thread_is_interrupted(t) && !exceptions_get_exception()) {
1550 /* Clear interrupted flag (Mauve test:
1551 gnu/testlet/java/lang/Thread/interrupt). */
1553 thread_set_interrupted(t, false);
1555 /* exceptions_throw_interruptedexception("sleep interrupted"); */
1556 exceptions_throw_interruptedexception();
1560 // (Note taken from classpath/vm/reference/java/lang/VMThread.java (sleep))
1561 // Note: JDK treats a zero length sleep is like Thread.yield(),
1562 // without checking the interrupted status of the thread. It's
1563 // unclear if this is a bug in the implementation or the spec.
1564 // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6213203 */
1565 if (millis == 0 && nanos == 0) {
1569 threads_calc_absolute_time(&wakeupTime, millis, nanos);
1571 threads_wait_with_timeout(t, &wakeupTime);
1573 interrupted = thread_is_interrupted(t);
1576 thread_set_interrupted(t, false);
1578 // An other exception could have been thrown
1579 // (e.g. ThreadDeathException).
1580 if (!exceptions_get_exception())
1581 exceptions_throw_interruptedexception();
1587 /* threads_yield ***************************************************************
1589 Yield to the scheduler.
1591 *******************************************************************************/
1593 void threads_yield(void)
1598 #if defined(ENABLE_TLH)
1600 void threads_tlh_add_frame() {
1601 tlh_add_frame(&(THREADOBJECT->tlh));
1604 void threads_tlh_remove_frame() {
1605 tlh_remove_frame(&(THREADOBJECT->tlh));
1614 * These are local overrides for various environment variables in Emacs.
1615 * Please do not remove this and leave it at the end of the file, where
1616 * Emacs will automagically detect them.
1617 * ---------------------------------------------------------------------
1620 * indent-tabs-mode: t
1624 * vim:noexpandtab:sw=4:ts=4: