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.hpp"
55 #include "threads/condition.hpp"
56 #include "threads/lock.hpp"
57 #include "threads/mutex.hpp"
58 #include "threads/threadlist.hpp"
59 #include "threads/thread.hpp"
61 #include "toolbox/logging.h"
63 #include "vm/jit/builtin.hpp"
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 #if defined(__DARWIN__)
103 /* Darwin has no working semaphore implementation. This one is taken
107 This is a very simple semaphore implementation for Darwin. It
108 is implemented in terms of pthreads calls so it isn't async signal
109 safe. This isn't a problem because signals aren't used to
110 suspend threads on Darwin.
113 static int sem_init(sem_t *sem, int pshared, int value)
118 sem->mutex = new Mutex();
119 sem->cond = new Condition();
125 static int sem_post(sem_t *sem)
130 sem->mutex->unlock();
135 static int sem_wait(sem_t *sem)
139 while (sem->value == 0) {
140 sem->cond->wait(sem->mutex);
144 sem->mutex->unlock();
149 static int sem_destroy(sem_t *sem)
156 #endif /* defined(__DARWIN__) */
159 /* startupinfo *****************************************************************
161 Struct used to pass info from threads_start_thread to
162 threads_startup_thread.
164 ******************************************************************************/
167 threadobject *thread; /* threadobject for this thread */
168 functionptr function; /* function to run in the new thread */
169 sem_t *psem; /* signals when thread has been entered */
170 /* in the thread list */
171 sem_t *psem_first; /* signals when pthread_create has returned */
175 /* prototypes *****************************************************************/
177 static void threads_calc_absolute_time(struct timespec *tm, s8 millis, s4 nanos);
180 /******************************************************************************/
181 /* GLOBAL VARIABLES */
182 /******************************************************************************/
184 /* the thread object of the current thread */
185 /* This is either a thread-local variable defined with __thread, or */
186 /* a thread-specific value stored with key threads_current_threadobject_key. */
187 #if defined(HAVE___THREAD)
188 __thread threadobject *thread_current;
190 pthread_key_t thread_current_key;
193 /* global mutex for stop-the-world */
194 static Mutex* stopworldlock;
196 #if defined(ENABLE_GC_CACAO)
197 /* global mutex for the GC */
198 static Mutex* mutex_gc;
201 /* global mutex and condition for joining threads on exit */
202 static Mutex* mutex_join;
203 static Condition* cond_join;
205 #if defined(ENABLE_GC_CACAO)
206 /* semaphore used for acknowleding thread suspension */
207 static sem_t suspend_ack;
211 /* threads_sem_init ************************************************************
213 Initialize a semaphore. Checks against errors and interruptions.
216 sem..............the semaphore to initialize
217 shared...........true if this semaphore will be shared between processes
218 value............the initial value for the semaphore
220 *******************************************************************************/
222 void threads_sem_init(sem_t *sem, bool shared, int value)
229 r = sem_init(sem, shared, value);
232 } while (errno == EINTR);
234 vm_abort("sem_init failed: %s", strerror(errno));
238 /* threads_sem_wait ************************************************************
240 Wait for a semaphore, non-interruptible.
242 IMPORTANT: Always use this function instead of `sem_wait` directly, as
243 `sem_wait` may be interrupted by signals!
246 sem..............the semaphore to wait on
248 *******************************************************************************/
250 void threads_sem_wait(sem_t *sem)
260 } while (errno == EINTR);
262 vm_abort("sem_wait failed: %s", strerror(errno));
266 /* threads_sem_post ************************************************************
268 Increase the count of a semaphore. Checks for errors.
271 sem..............the semaphore to increase the count of
273 *******************************************************************************/
275 void threads_sem_post(sem_t *sem)
281 /* unlike sem_wait, sem_post is not interruptible */
287 vm_abort("sem_post failed: %s", strerror(errno));
291 /* threads_stopworld ***********************************************************
293 Stops the world from turning. All threads except the calling one
294 are suspended. The function returns as soon as all threads have
295 acknowledged their suspension.
297 *******************************************************************************/
299 #if defined(ENABLE_GC_CACAO)
300 void threads_stopworld(void)
302 #if !defined(__DARWIN__) && !defined(__CYGWIN__)
309 stopworldlock->lock();
311 /* lock the threads lists */
315 #if defined(__DARWIN__)
316 /*threads_cast_darwinstop();*/
318 #elif defined(__CYGWIN__)
324 DEBUGTHREADS("stops World", self);
328 /* suspend all running threads */
329 for (t = threadlist_first(); t != NULL; t = threadlist_next(t)) {
330 /* don't send the signal to ourself */
335 /* don't send the signal to NEW threads (because they are not
336 completely initialized) */
338 if (t->state == THREAD_STATE_NEW)
341 /* send the signal */
343 result = threads_suspend_thread(t, SUSPEND_REASON_STOPWORLD);
346 /* increase threads count */
351 /* wait for all threads signaled to suspend */
352 for (i = 0; i < count; i++)
353 threads_sem_wait(&suspend_ack);
356 /* ATTENTION: Don't unlock the threads-lists here so that
357 non-signaled NEW threads can't change their state and execute
363 /* threads_startworld **********************************************************
365 Starts the world again after it has previously been stopped.
367 *******************************************************************************/
369 #if defined(ENABLE_GC_CACAO)
370 void threads_startworld(void)
372 #if !defined(__DARWIN__) && !defined(__CYGWIN__)
379 #if defined(__DARWIN__)
380 /*threads_cast_darwinresume();*/
382 #elif defined(__IRIX__)
383 threads_cast_irixresume();
384 #elif defined(__CYGWIN__)
390 DEBUGTHREADS("starts World", self);
394 /* resume all thread we haltet */
395 for (t = threadlist_first(); t != NULL; t = threadlist_next(t)) {
396 /* don't send the signal to ourself */
401 /* don't send the signal to NEW threads (because they are not
402 completely initialized) */
404 if (t->state == THREAD_STATE_NEW)
407 /* send the signal */
409 result = threads_resume_thread(t);
412 /* increase threads count */
417 /* wait for all threads signaled to suspend */
418 for (i = 0; i < count; i++)
419 threads_sem_wait(&suspend_ack);
423 /* unlock the threads lists */
427 stopworldlock->unlock();
432 /* threads_impl_thread_clear ***************************************************
434 Clears all fields in threadobject the way an MZERO would have
435 done. MZERO cannot be used anymore because it would mess up the
439 t....the threadobject
441 *******************************************************************************/
443 void threads_impl_thread_clear(threadobject *t)
455 #if defined(__DARWIN__)
459 t->interrupted = false;
462 t->suspended = false;
463 t->suspend_reason = 0;
467 t->_exceptionptr = NULL;
468 t->_stackframeinfo = NULL;
469 t->_localref_table = NULL;
471 #if defined(ENABLE_INTRP)
472 t->_global_sp = NULL;
475 #if defined(ENABLE_GC_CACAO)
476 t->gc_critical = false;
482 // Simply reuse the existing dump memory.
485 /* threads_impl_thread_reuse ***************************************************
487 Resets some implementation fields in threadobject. This was
488 previously done in threads_impl_thread_new.
491 t....the threadobject
493 *******************************************************************************/
495 void threads_impl_thread_reuse(threadobject *t)
497 /* get the pthread id */
499 t->tid = pthread_self();
501 #if defined(ENABLE_DEBUG_FILTER)
502 /* Initialize filter counters */
503 t->filterverbosecallctr[0] = 0;
504 t->filterverbosecallctr[1] = 0;
508 t->tracejavacallindent = 0;
509 t->tracejavacallcount = 0;
516 /* not really needed */
517 t->flc_object = NULL;
519 #if defined(ENABLE_TLH)
520 tlh_destroy(&(t->tlh));
526 /* threads_impl_thread_free ****************************************************
528 Cleanup thread stuff.
531 t....the threadobject
533 *******************************************************************************/
537 void threads_impl_thread_free(threadobject *t)
541 /* Destroy the mutex and the condition. */
545 result = pthread_cond_destroy(&(t->flc_cond));
548 vm_abort_errnum(result, "threads_impl_thread_free: pthread_cond_destroy failed");
552 result = pthread_cond_destroy(&(t->waitcond));
555 vm_abort_errnum(result, "threads_impl_thread_free: pthread_cond_destroy failed");
557 delete t->suspendmutex;
559 result = pthread_cond_destroy(&(t->suspendcond));
562 vm_abort_errnum(result, "threads_impl_thread_free: pthread_cond_destroy failed");
567 /* threads_impl_preinit ********************************************************
569 Do some early initialization of stuff required.
571 ATTENTION: Do NOT use any Java heap allocation here, as gc_init()
572 is called AFTER this function!
574 *******************************************************************************/
576 void threads_impl_preinit(void)
580 stopworldlock = new Mutex();
582 /* initialize exit mutex and condition (on exit we join all
585 mutex_join = new Mutex();
586 cond_join = new Condition();
588 #if defined(ENABLE_GC_CACAO)
589 /* initialize the GC mutex & suspend semaphore */
591 mutex_gc = new Mutex();
592 threads_sem_init(&suspend_ack, 0, 0);
595 #if !defined(HAVE___THREAD)
596 result = pthread_key_create(&thread_current_key, NULL);
598 vm_abort_errnum(result, "threads_impl_preinit: pthread_key_create failed");
603 /* threads_mutex_gc_lock *******************************************************
605 Enter the global GC mutex.
607 *******************************************************************************/
609 #if defined(ENABLE_GC_CACAO)
610 void threads_mutex_gc_lock(void)
617 /* threads_mutex_gc_unlock *****************************************************
619 Leave the global GC mutex.
621 *******************************************************************************/
623 #if defined(ENABLE_GC_CACAO)
624 void threads_mutex_gc_unlock(void)
630 /* threads_mutex_join_lock *****************************************************
632 Enter the join mutex.
634 *******************************************************************************/
636 void threads_mutex_join_lock(void)
642 /* threads_mutex_join_unlock ***************************************************
644 Leave the join mutex.
646 *******************************************************************************/
648 void threads_mutex_join_unlock(void)
650 mutex_join->unlock();
654 /* threads_impl_init ***********************************************************
656 Initializes the implementation specific bits.
658 *******************************************************************************/
660 void threads_impl_init(void)
665 threads_set_thread_priority(pthread_self(), NORM_PRIORITY);
667 /* Initialize the thread attribute object. */
669 result = pthread_attr_init(&attr);
672 vm_abort_errnum(result, "threads_impl_init: pthread_attr_init failed");
674 result = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
677 vm_abort_errnum(result, "threads_impl_init: pthread_attr_setdetachstate failed");
681 /* threads_startup_thread ******************************************************
683 Thread startup function called by pthread_create.
685 Thread which have a startup.function != NULL are marked as internal
686 threads. All other threads are threated as normal Java threads.
688 NOTE: This function is not called directly by pthread_create. The Boehm GC
689 inserts its own GC_start_routine in between, which then calls
693 arg..........the argument passed to pthread_create, ie. a pointer to
694 a startupinfo struct. CAUTION: When the `psem` semaphore
695 is posted, the startupinfo struct becomes invalid! (It
696 is allocated on the stack of threads_start_thread.)
698 ******************************************************************************/
700 static void *threads_startup_thread(void *arg)
702 startupinfo *startup;
707 functionptr function;
709 #if defined(ENABLE_GC_BOEHM)
710 # if !defined(__DARWIN__)
711 struct GC_stack_base sb;
716 #if defined(ENABLE_INTRP)
717 u1 *intrp_thread_stack;
720 #if defined(ENABLE_INTRP)
721 /* create interpreter stack */
724 intrp_thread_stack = GCMNEW(u1, opt_stacksize);
725 MSET(intrp_thread_stack, 0, u1, opt_stacksize);
728 intrp_thread_stack = NULL;
731 /* get passed startupinfo structure and the values in there */
733 startup = (startupinfo*) arg;
736 function = startup->function;
737 psem = startup->psem;
739 /* Seems like we've encountered a situation where thread->tid was
740 not set by pthread_create. We alleviate this problem by waiting
741 for pthread_create to return. */
743 threads_sem_wait(startup->psem_first);
745 #if defined(__DARWIN__)
746 t->mach_thread = mach_thread_self();
749 /* Now that we are in the new thread, we can store the internal
750 thread data-structure in the TSD. */
752 thread_set_current(t);
754 #if defined(ENABLE_GC_BOEHM)
755 # if defined(__DARWIN__)
756 // This is currently not implemented in Boehm-GC. Just fail silently.
758 /* Register the thread with Boehm-GC. This must happen before the
759 thread allocates any memory from the GC heap.*/
761 result = GC_get_stack_base(&sb);
764 vm_abort("threads_startup_thread: GC_get_stack_base failed: result=%d", result);
766 GC_register_my_thread(&sb);
770 // Get the java.lang.Thread object for this thread.
771 java_handle_t* object = thread_get_object(t);
772 java_lang_Thread jlt(object);
774 /* set our priority */
776 threads_set_thread_priority(t->tid, jlt.get_priority());
778 /* Thread is completely initialized. */
780 thread_set_state_runnable(t);
782 /* tell threads_startup_thread that we registered ourselves */
783 /* CAUTION: *startup becomes invalid with this! */
786 threads_sem_post(psem);
788 #if defined(ENABLE_INTRP)
789 /* set interpreter stack */
792 thread->_global_sp = (Cell *) (intrp_thread_stack + opt_stacksize);
795 #if defined(ENABLE_JVMTI)
796 /* fire thread start event */
799 jvmti_ThreadStartEnd(JVMTI_EVENT_THREAD_START);
802 DEBUGTHREADS("starting", t);
804 /* find and run the Thread.run()V method if no other function was passed */
806 if (function == NULL) {
807 #if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
808 /* We need to start the run method of
809 java.lang.VMThread. Since this is a final class, we can use
810 the class object directly. */
812 c = class_java_lang_VMThread;
813 #elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK) || defined(WITH_JAVA_RUNTIME_LIBRARY_CLDC1_1)
814 LLNI_class_get(object, c);
816 # error unknown classpath configuration
819 m = class_resolveclassmethod(c, utf_run, utf_void__void, c, true);
822 vm_abort("threads_startup_thread: run() method not found in class");
824 /* set ThreadMXBean variables */
826 /* _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount++; */
827 /* _Jv_jvm->java_lang_management_ThreadMXBean_TotalStartedThreadCount++; */
829 /* if (_Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount > */
830 /* _Jv_jvm->java_lang_management_ThreadMXBean_PeakThreadCount) */
831 /* _Jv_jvm->java_lang_management_ThreadMXBean_PeakThreadCount = */
832 /* _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount; */
835 #if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
837 // We need to start the run method of java.lang.VMThread.
838 java_lang_VMThread jlvmt(jlt.get_vmThread());
839 java_handle_t* h = jlvmt.get_handle();
841 #elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK) || defined(WITH_JAVA_RUNTIME_LIBRARY_CLDC1_1)
843 java_handle_t* h = jlt.get_handle();
846 # error unknown classpath configuration
849 /* Run the thread. */
851 (void) vm_call_method(m, h);
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 /* call passed function, e.g. finalizer_thread */
870 DEBUGTHREADS("stopping", t);
872 #if defined(ENABLE_JVMTI)
873 /* fire thread end event */
876 jvmti_ThreadStartEnd(JVMTI_EVENT_THREAD_END);
879 /* We ignore the return value. */
881 (void) thread_detach_current_thread();
883 /* set ThreadMXBean variables */
885 /* _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount--; */
892 /* threads_impl_thread_start ***************************************************
894 Start a thread in the JVM. Both (vm internal and java) thread
898 thread....the thread object
899 f.........function to run in the new thread. NULL means that the
900 "run" method of the object `t` should be called
902 ******************************************************************************/
904 void threads_impl_thread_start(threadobject *thread, functionptr f)
912 /* fill startupinfo structure passed by pthread_create to
913 * threads_startup_thread */
915 startup.thread = thread;
916 startup.function = f; /* maybe we don't call Thread.run()V */
918 startup.psem_first = &sem_first;
920 threads_sem_init(&sem, 0, 0);
921 threads_sem_init(&sem_first, 0, 0);
923 /* Initialize thread attributes. */
925 result = pthread_attr_init(&attr);
928 vm_abort_errnum(result, "threads_impl_thread_start: pthread_attr_init failed");
930 result = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
933 vm_abort_errnum(result, "threads_impl_thread_start: pthread_attr_setdetachstate failed");
935 /* initialize thread stacksize */
937 result = pthread_attr_setstacksize(&attr, opt_stacksize);
940 vm_abort_errnum(result, "threads_impl_thread_start: pthread_attr_setstacksize failed");
942 /* create the thread */
944 result = pthread_create(&(thread->tid), &attr, threads_startup_thread, &startup);
947 vm_abort_errnum(result, "threads_impl_thread_start: pthread_create failed");
949 /* destroy the thread attributes */
951 result = pthread_attr_destroy(&attr);
954 vm_abort_errnum(result, "threads_impl_thread_start: pthread_attr_destroy failed");
956 /* signal that pthread_create has returned, so thread->tid is valid */
958 threads_sem_post(&sem_first);
960 /* wait here until the thread has entered itself into the thread list */
962 threads_sem_wait(&sem);
967 sem_destroy(&sem_first);
971 /* threads_set_thread_priority *************************************************
973 Set the priority of the given thread.
976 tid..........thread id
977 priority.....priority to set
979 ******************************************************************************/
981 void threads_set_thread_priority(pthread_t tid, int priority)
983 struct sched_param schedp;
986 pthread_getschedparam(tid, &policy, &schedp);
987 schedp.sched_priority = priority;
988 pthread_setschedparam(tid, policy, &schedp);
993 * Detaches the current thread from the VM.
995 * @return true on success, false otherwise
997 bool thread_detach_current_thread(void)
999 threadobject* t = thread_get_current();
1005 /* If the given thread has already been detached, this operation
1008 if (thread_is_attached(t) == false)
1011 DEBUGTHREADS("detaching", t);
1013 java_handle_t* object = thread_get_object(t);
1014 java_lang_Thread jlt(object);
1016 #if defined(ENABLE_JAVASE)
1017 java_handle_t* group = jlt.get_group();
1019 /* If there's an uncaught exception, call uncaughtException on the
1020 thread's exception handler, or the thread's group if this is
1023 java_handle_t* e = exceptions_get_and_clear_exception();
1026 /* We use the type void* for handler here, as it's not trivial
1027 to build the java_lang_Thread_UncaughtExceptionHandler
1028 header file with cacaoh. */
1030 # if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
1032 java_handle_t* handler = jlt.get_exceptionHandler();
1034 # elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK)
1036 java_handle_t* handler = jlt.get_uncaughtExceptionHandler();
1043 if (handler != NULL) {
1044 LLNI_class_get(handler, c);
1045 h = (java_handle_t *) handler;
1048 LLNI_class_get(group, c);
1049 h = (java_handle_t *) group;
1052 methodinfo* m = class_resolveclassmethod(c,
1053 utf_uncaughtException,
1054 utf_java_lang_Thread_java_lang_Throwable__V,
1061 (void) vm_call_method(m, h, object, e);
1063 if (exceptions_get_exception())
1067 /* XXX TWISTI: should all threads be in a ThreadGroup? */
1069 /* Remove thread from the thread group. */
1071 if (group != NULL) {
1073 LLNI_class_get(group, c);
1075 # if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
1076 methodinfo* m = class_resolveclassmethod(c,
1078 utf_java_lang_Thread__V,
1079 class_java_lang_ThreadGroup,
1081 # elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK)
1082 methodinfo* m = class_resolveclassmethod(c,
1084 utf_java_lang_Thread__V,
1085 class_java_lang_ThreadGroup,
1088 # error unknown classpath configuration
1094 (void) vm_call_method(m, group, object);
1096 if (exceptions_get_exception())
1099 // Clear the ThreadGroup in the Java thread object (Mauve
1100 // test: gnu/testlet/java/lang/Thread/getThreadGroup).
1101 jlt.set_group(NULL);
1105 /* Thread has terminated. */
1107 thread_set_state_terminated(t);
1109 /* Notify all threads waiting on this thread. These are joining
1112 /* XXX Care about exceptions? */
1113 (void) lock_monitor_enter(jlt.get_handle());
1115 lock_notify_all_object(jlt.get_handle());
1117 /* XXX Care about exceptions? */
1118 (void) lock_monitor_exit(jlt.get_handle());
1120 /* Enter the join-mutex before calling thread_free, so
1121 threads_join_all_threads gets the correct number of non-daemon
1124 threads_mutex_join_lock();
1126 /* Free the internal thread data-structure. */
1130 /* Signal that this thread has finished and leave the mutex. */
1132 cond_join->signal();
1133 threads_mutex_join_unlock();
1139 /* threads_suspend_thread ******************************************************
1141 Suspend the passed thread. Execution stops until the thread
1142 is explicitly resumend again.
1145 reason.....Reason for suspending this thread.
1147 *******************************************************************************/
1149 bool threads_suspend_thread(threadobject *thread, s4 reason)
1151 /* acquire the suspendmutex */
1152 thread->suspendmutex->lock();
1154 if (thread->suspended) {
1155 thread->suspendmutex->unlock();
1159 /* set the reason for the suspension */
1160 thread->suspend_reason = reason;
1162 /* send the suspend signal to the thread */
1163 assert(thread != THREADOBJECT);
1164 if (pthread_kill(thread->tid, SIGUSR1) != 0)
1165 vm_abort("threads_suspend_thread: pthread_kill failed: %s",
1168 /* REMEMBER: do not release the suspendmutex, this is done
1169 by the thread itself in threads_suspend_ack(). */
1175 /* threads_suspend_ack *********************************************************
1177 Acknowledges the suspension of the current thread.
1180 pc.....The PC where the thread suspended its execution.
1181 sp.....The SP before the thread suspended its execution.
1183 *******************************************************************************/
1185 #if defined(ENABLE_GC_CACAO)
1186 void threads_suspend_ack(u1* pc, u1* sp)
1188 threadobject *thread;
1190 thread = THREADOBJECT;
1192 assert(thread->suspend_reason != 0);
1194 /* TODO: remember dump memory size */
1196 /* inform the GC about the suspension */
1197 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD && gc_pending) {
1199 /* check if the GC wants to leave the thread running */
1200 if (!gc_suspend(thread, pc, sp)) {
1202 /* REMEMBER: we do not unlock the suspendmutex because the thread
1203 will suspend itself again at a later time */
1209 /* mark this thread as suspended and remember the PC */
1211 thread->suspended = true;
1213 /* if we are stopping the world, we should send a global ack */
1214 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD) {
1215 threads_sem_post(&suspend_ack);
1218 DEBUGTHREADS("suspending", thread);
1220 /* release the suspension mutex and wait till we are resumed */
1221 thread->suspendcond->wait(thread->suspendmutex);
1223 DEBUGTHREADS("resuming", thread);
1225 /* if we are stopping the world, we should send a global ack */
1226 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD) {
1227 threads_sem_post(&suspend_ack);
1230 /* TODO: free dump memory */
1232 /* release the suspendmutex */
1233 thread->suspendmutex->unlock();
1238 /* threads_resume_thread *******************************************************
1240 Resumes the execution of the passed thread.
1242 *******************************************************************************/
1244 #if defined(ENABLE_GC_CACAO)
1245 bool threads_resume_thread(threadobject *thread)
1247 /* acquire the suspendmutex */
1248 thread->suspendmutex->lock();
1250 if (!thread->suspended) {
1251 thread->suspendmutex->unlock();
1255 thread->suspended = false;
1257 /* tell everyone that the thread should resume */
1258 assert(thread != THREADOBJECT);
1259 thread->suspendcond->broadcast();
1261 /* release the suspendmutex */
1262 thread->suspendmutex->unlock();
1269 /* threads_join_all_threads ****************************************************
1271 Join all non-daemon threads.
1273 *******************************************************************************/
1275 void threads_join_all_threads(void)
1279 /* get current thread */
1283 /* This thread is waiting for all non-daemon threads to exit. */
1285 thread_set_state_waiting(t);
1287 /* enter join mutex */
1289 threads_mutex_join_lock();
1291 /* Wait for condition as long as we have non-daemon threads. We
1292 compare against 1 because the current (main thread) is also a
1293 non-daemon thread. */
1295 while (ThreadList::get_number_of_non_daemon_threads() > 1)
1296 cond_join->wait(mutex_join);
1298 /* leave join mutex */
1300 threads_mutex_join_unlock();
1304 /* threads_timespec_earlier ****************************************************
1306 Return true if timespec tv1 is earlier than timespec tv2.
1309 tv1..........first timespec
1310 tv2..........second timespec
1313 true, if the first timespec is earlier
1315 *******************************************************************************/
1317 static inline bool threads_timespec_earlier(const struct timespec *tv1,
1318 const struct timespec *tv2)
1320 return (tv1->tv_sec < tv2->tv_sec)
1322 (tv1->tv_sec == tv2->tv_sec && tv1->tv_nsec < tv2->tv_nsec);
1326 /* threads_current_time_is_earlier_than ****************************************
1328 Check if the current time is earlier than the given timespec.
1331 tv...........the timespec to compare against
1334 true, if the current time is earlier
1336 *******************************************************************************/
1338 static bool threads_current_time_is_earlier_than(const struct timespec *tv)
1340 struct timeval tvnow;
1341 struct timespec tsnow;
1343 /* get current time */
1345 if (gettimeofday(&tvnow, NULL) != 0)
1346 vm_abort("gettimeofday failed: %s\n", strerror(errno));
1348 /* convert it to a timespec */
1350 tsnow.tv_sec = tvnow.tv_sec;
1351 tsnow.tv_nsec = tvnow.tv_usec * 1000;
1353 /* compare current time with the given timespec */
1355 return threads_timespec_earlier(&tsnow, tv);
1359 /* threads_wait_with_timeout ***************************************************
1361 Wait until the given point in time on a monitor until either
1362 we are notified, we are interrupted, or the time is up.
1365 t............the current thread
1366 wakeupTime...absolute (latest) wakeup time
1367 If both tv_sec and tv_nsec are zero, this function
1368 waits for an unlimited amount of time.
1370 *******************************************************************************/
1372 static void threads_wait_with_timeout(threadobject *t, struct timespec *wakeupTime)
1374 // Acquire the waitmutex.
1375 t->waitmutex->lock();
1377 /* wait on waitcond */
1379 if (wakeupTime->tv_sec || wakeupTime->tv_nsec) {
1381 while (!t->interrupted && !t->signaled
1382 && threads_current_time_is_earlier_than(wakeupTime))
1384 thread_set_state_timed_waiting(t);
1386 t->waitcond->timedwait(t->waitmutex, wakeupTime);
1388 thread_set_state_runnable(t);
1393 while (!t->interrupted && !t->signaled) {
1394 thread_set_state_waiting(t);
1396 t->waitcond->wait(t->waitmutex);
1398 thread_set_state_runnable(t);
1402 // Release the waitmutex.
1403 t->waitmutex->unlock();
1407 /* threads_wait_with_timeout_relative ******************************************
1409 Wait for the given maximum amount of time on a monitor until either
1410 we are notified, we are interrupted, or the time is up.
1413 t............the current thread
1414 millis.......milliseconds to wait
1415 nanos........nanoseconds to wait
1417 *******************************************************************************/
1419 void threads_wait_with_timeout_relative(threadobject *thread, s8 millis,
1422 struct timespec wakeupTime;
1424 /* calculate the the (latest) wakeup time */
1426 threads_calc_absolute_time(&wakeupTime, millis, nanos);
1430 threads_wait_with_timeout(thread, &wakeupTime);
1434 /* threads_calc_absolute_time **************************************************
1436 Calculate the absolute point in time a given number of ms and ns from now.
1439 millis............milliseconds from now
1440 nanos.............nanoseconds from now
1443 *tm...............receives the timespec of the absolute point in time
1445 *******************************************************************************/
1447 static void threads_calc_absolute_time(struct timespec *tm, s8 millis, s4 nanos)
1449 if ((millis != 0x7fffffffffffffffLLU) && (millis || nanos)) {
1452 gettimeofday(&tv, NULL);
1453 tv.tv_sec += millis / 1000;
1455 nsec = tv.tv_usec * 1000 + (s4) millis * 1000000 + nanos;
1456 tm->tv_sec = tv.tv_sec + nsec / 1000000000;
1457 tm->tv_nsec = nsec % 1000000000;
1466 /* threads_thread_interrupt ****************************************************
1468 Interrupt the given thread.
1470 The thread gets the "waitcond" signal and
1471 its interrupted flag is set to true.
1474 thread............the thread to interrupt
1476 *******************************************************************************/
1478 void threads_thread_interrupt(threadobject *t)
1480 /* Signal the thread a "waitcond" and tell it that it has been
1483 t->waitmutex->lock();
1485 DEBUGTHREADS("interrupted", t);
1487 /* Interrupt blocking system call using a signal. */
1489 pthread_kill(t->tid, Signal_INTERRUPT_SYSTEM_CALL);
1491 t->waitcond->signal();
1493 t->interrupted = true;
1495 t->waitmutex->unlock();
1500 * Sleep the current thread for the specified amount of time.
1502 * @param millis Milliseconds to sleep.
1503 * @param nanos Nanoseconds to sleep.
1505 void threads_sleep(int64_t millis, int32_t nanos)
1508 struct timespec wakeupTime;
1512 /* exceptions_throw_illegalargumentexception("timeout value is negative"); */
1513 exceptions_throw_illegalargumentexception();
1517 t = thread_get_current();
1519 if (thread_is_interrupted(t) && !exceptions_get_exception()) {
1520 /* Clear interrupted flag (Mauve test:
1521 gnu/testlet/java/lang/Thread/interrupt). */
1523 thread_set_interrupted(t, false);
1525 /* exceptions_throw_interruptedexception("sleep interrupted"); */
1526 exceptions_throw_interruptedexception();
1530 // (Note taken from classpath/vm/reference/java/lang/VMThread.java (sleep))
1531 // Note: JDK treats a zero length sleep is like Thread.yield(),
1532 // without checking the interrupted status of the thread. It's
1533 // unclear if this is a bug in the implementation or the spec.
1534 // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6213203 */
1535 if (millis == 0 && nanos == 0) {
1539 threads_calc_absolute_time(&wakeupTime, millis, nanos);
1541 threads_wait_with_timeout(t, &wakeupTime);
1543 interrupted = thread_is_interrupted(t);
1546 thread_set_interrupted(t, false);
1548 // An other exception could have been thrown
1549 // (e.g. ThreadDeathException).
1550 if (!exceptions_get_exception())
1551 exceptions_throw_interruptedexception();
1557 /* threads_yield ***************************************************************
1559 Yield to the scheduler.
1561 *******************************************************************************/
1563 void threads_yield(void)
1568 #if defined(ENABLE_TLH)
1570 void threads_tlh_add_frame() {
1571 tlh_add_frame(&(THREADOBJECT->tlh));
1574 void threads_tlh_remove_frame() {
1575 tlh_remove_frame(&(THREADOBJECT->tlh));
1582 * These are local overrides for various environment variables in Emacs.
1583 * Please do not remove this and leave it at the end of the file, where
1584 * Emacs will automagically detect them.
1585 * ---------------------------------------------------------------------
1588 * indent-tabs-mode: t
1592 * vim:noexpandtab:sw=4:ts=4: