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 */
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/javaobjects.hpp"
70 #include "vm/options.h"
72 #include "vm/signallocal.hpp"
73 #include "vm/string.hpp"
76 #if defined(ENABLE_STATISTICS)
77 # include "vm/statistics.h"
80 #include "vm/jit/asmpart.h"
82 #if !defined(__DARWIN__)
83 # include <semaphore.h>
86 #if defined(__LINUX__)
87 # define GC_LINUX_THREADS
88 #elif defined(__IRIX__)
89 # define GC_IRIX_THREADS
90 #elif defined(__DARWIN__)
91 # define GC_DARWIN_THREADS
94 #if defined(ENABLE_GC_BOEHM)
95 /* We need to include Boehm's gc.h here because it overrides
96 pthread_create and friends. */
97 # include "mm/boehm-gc/include/gc.h"
100 #if defined(ENABLE_JVMTI)
101 #include "native/jvmti/cacaodbg.h"
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_clear ***************************************************
437 Clears all fields in threadobject the way an MZERO would have
438 done. MZERO cannot be used anymore because it would mess up the
442 t....the threadobject
444 *******************************************************************************/
446 void threads_impl_thread_clear(threadobject *t)
458 #if defined(__DARWIN__)
462 t->interrupted = false;
465 t->suspended = false;
466 t->suspend_reason = 0;
470 t->_exceptionptr = NULL;
471 t->_stackframeinfo = NULL;
472 t->_localref_table = NULL;
474 #if defined(ENABLE_INTRP)
475 t->_global_sp = NULL;
478 #if defined(ENABLE_GC_CACAO)
479 t->gc_critical = false;
485 // Simply reuse the existing dump memory.
488 /* threads_impl_thread_reuse ***************************************************
490 Resets some implementation fields in threadobject. This was
491 previously done in threads_impl_thread_new.
494 t....the threadobject
496 *******************************************************************************/
498 void threads_impl_thread_reuse(threadobject *t)
500 /* get the pthread id */
502 t->tid = pthread_self();
504 #if defined(ENABLE_DEBUG_FILTER)
505 /* Initialize filter counters */
506 t->filterverbosecallctr[0] = 0;
507 t->filterverbosecallctr[1] = 0;
511 t->tracejavacallindent = 0;
512 t->tracejavacallcount = 0;
519 /* not really needed */
520 t->flc_object = NULL;
522 #if defined(ENABLE_TLH)
523 tlh_destroy(&(t->tlh));
529 /* threads_impl_thread_free ****************************************************
531 Cleanup thread stuff.
534 t....the threadobject
536 *******************************************************************************/
540 void threads_impl_thread_free(threadobject *t)
544 /* Destroy the mutex and the condition. */
548 result = pthread_cond_destroy(&(t->flc_cond));
551 os::abort_errnum(result, "threads_impl_thread_free: pthread_cond_destroy failed");
555 result = pthread_cond_destroy(&(t->waitcond));
558 os::abort_errnum(result, "threads_impl_thread_free: pthread_cond_destroy failed");
560 delete t->suspendmutex;
562 result = pthread_cond_destroy(&(t->suspendcond));
565 os::abort_errnum(result, "threads_impl_thread_free: pthread_cond_destroy failed");
570 /* threads_impl_preinit ********************************************************
572 Do some early initialization of stuff required.
574 ATTENTION: Do NOT use any Java heap allocation here, as gc_init()
575 is called AFTER this function!
577 *******************************************************************************/
579 void threads_impl_preinit(void)
583 stopworldlock = new Mutex();
585 /* initialize exit mutex and condition (on exit we join all
588 mutex_join = new Mutex();
589 cond_join = new Condition();
591 #if defined(ENABLE_GC_CACAO)
592 /* initialize the GC mutex & suspend semaphore */
594 mutex_gc = new Mutex();
595 threads_sem_init(&suspend_ack, 0, 0);
598 #if !defined(HAVE___THREAD)
599 result = pthread_key_create(&thread_current_key, NULL);
601 os::abort_errnum(result, "threads_impl_preinit: pthread_key_create failed");
606 /* threads_mutex_gc_lock *******************************************************
608 Enter the global GC mutex.
610 *******************************************************************************/
612 #if defined(ENABLE_GC_CACAO)
613 void threads_mutex_gc_lock(void)
620 /* threads_mutex_gc_unlock *****************************************************
622 Leave the global GC mutex.
624 *******************************************************************************/
626 #if defined(ENABLE_GC_CACAO)
627 void threads_mutex_gc_unlock(void)
633 /* threads_mutex_join_lock *****************************************************
635 Enter the join mutex.
637 *******************************************************************************/
639 void threads_mutex_join_lock(void)
645 /* threads_mutex_join_unlock ***************************************************
647 Leave the join mutex.
649 *******************************************************************************/
651 void threads_mutex_join_unlock(void)
653 mutex_join->unlock();
657 /* threads_impl_init ***********************************************************
659 Initializes the implementation specific bits.
661 *******************************************************************************/
663 void threads_impl_init(void)
668 threads_set_thread_priority(pthread_self(), NORM_PRIORITY);
670 /* Initialize the thread attribute object. */
672 result = pthread_attr_init(&attr);
675 os::abort_errnum(result, "threads_impl_init: pthread_attr_init failed");
677 result = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
680 os::abort_errnum(result, "threads_impl_init: pthread_attr_setdetachstate failed");
684 /* threads_startup_thread ******************************************************
686 Thread startup function called by pthread_create.
688 Thread which have a startup.function != NULL are marked as internal
689 threads. All other threads are threated as normal Java threads.
691 NOTE: This function is not called directly by pthread_create. The Boehm GC
692 inserts its own GC_start_routine in between, which then calls
696 arg..........the argument passed to pthread_create, ie. a pointer to
697 a startupinfo struct. CAUTION: When the `psem` semaphore
698 is posted, the startupinfo struct becomes invalid! (It
699 is allocated on the stack of threads_start_thread.)
701 ******************************************************************************/
703 static void *threads_startup_thread(void *arg)
705 startupinfo *startup;
710 functionptr function;
712 #if defined(ENABLE_GC_BOEHM)
713 # if !defined(__DARWIN__)
714 struct GC_stack_base sb;
719 #if defined(ENABLE_INTRP)
720 u1 *intrp_thread_stack;
723 #if defined(ENABLE_INTRP)
724 /* create interpreter stack */
727 intrp_thread_stack = GCMNEW(u1, opt_stacksize);
728 MSET(intrp_thread_stack, 0, u1, opt_stacksize);
731 intrp_thread_stack = NULL;
734 /* get passed startupinfo structure and the values in there */
736 startup = (startupinfo*) arg;
739 function = startup->function;
740 psem = startup->psem;
742 /* Seems like we've encountered a situation where thread->tid was
743 not set by pthread_create. We alleviate this problem by waiting
744 for pthread_create to return. */
746 threads_sem_wait(startup->psem_first);
748 #if defined(__DARWIN__)
749 t->mach_thread = mach_thread_self();
752 /* Now that we are in the new thread, we can store the internal
753 thread data-structure in the TSD. */
755 thread_set_current(t);
757 #if defined(ENABLE_GC_BOEHM)
758 # if defined(__DARWIN__)
759 // This is currently not implemented in Boehm-GC. Just fail silently.
761 /* Register the thread with Boehm-GC. This must happen before the
762 thread allocates any memory from the GC heap.*/
764 result = GC_get_stack_base(&sb);
767 vm_abort("threads_startup_thread: GC_get_stack_base failed: result=%d", result);
769 GC_register_my_thread(&sb);
773 // Get the java.lang.Thread object for this thread.
774 java_handle_t* object = thread_get_object(t);
775 java_lang_Thread jlt(object);
777 /* set our priority */
779 threads_set_thread_priority(t->tid, jlt.get_priority());
781 /* Thread is completely initialized. */
783 thread_set_state_runnable(t);
785 /* tell threads_startup_thread that we registered ourselves */
786 /* CAUTION: *startup becomes invalid with this! */
789 threads_sem_post(psem);
791 #if defined(ENABLE_INTRP)
792 /* set interpreter stack */
795 thread->_global_sp = (Cell *) (intrp_thread_stack + opt_stacksize);
798 #if defined(ENABLE_JVMTI)
799 /* fire thread start event */
802 jvmti_ThreadStartEnd(JVMTI_EVENT_THREAD_START);
805 DEBUGTHREADS("starting", t);
807 /* find and run the Thread.run()V method if no other function was passed */
809 if (function == NULL) {
810 #if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
811 /* We need to start the run method of
812 java.lang.VMThread. Since this is a final class, we can use
813 the class object directly. */
815 c = class_java_lang_VMThread;
816 #elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK) || defined(WITH_JAVA_RUNTIME_LIBRARY_CLDC1_1)
817 LLNI_class_get(object, c);
819 # error unknown classpath configuration
822 m = class_resolveclassmethod(c, utf_run, utf_void__void, c, true);
825 vm_abort("threads_startup_thread: run() method not found in class");
827 #if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
829 // We need to start the run method of java.lang.VMThread.
830 java_lang_VMThread jlvmt(jlt.get_vmThread());
831 java_handle_t* h = jlvmt.get_handle();
833 #elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK) || defined(WITH_JAVA_RUNTIME_LIBRARY_CLDC1_1)
835 java_handle_t* h = jlt.get_handle();
838 # error unknown classpath configuration
841 /* Run the thread. */
843 (void) vm_call_method(m, h);
846 /* call passed function, e.g. finalizer_thread */
851 DEBUGTHREADS("stopping", t);
853 #if defined(ENABLE_JVMTI)
854 /* fire thread end event */
857 jvmti_ThreadStartEnd(JVMTI_EVENT_THREAD_END);
860 /* We ignore the return value. */
862 (void) thread_detach_current_thread();
868 /* threads_impl_thread_start ***************************************************
870 Start a thread in the JVM. Both (vm internal and java) thread
874 thread....the thread object
875 f.........function to run in the new thread. NULL means that the
876 "run" method of the object `t` should be called
878 ******************************************************************************/
880 void threads_impl_thread_start(threadobject *thread, functionptr f)
888 /* fill startupinfo structure passed by pthread_create to
889 * threads_startup_thread */
891 startup.thread = thread;
892 startup.function = f; /* maybe we don't call Thread.run()V */
894 startup.psem_first = &sem_first;
896 threads_sem_init(&sem, 0, 0);
897 threads_sem_init(&sem_first, 0, 0);
899 /* Initialize thread attributes. */
901 result = pthread_attr_init(&attr);
904 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_init failed");
906 result = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
909 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_setdetachstate failed");
911 /* initialize thread stacksize */
913 result = pthread_attr_setstacksize(&attr, opt_stacksize);
916 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_setstacksize failed");
918 /* create the thread */
920 result = pthread_create(&(thread->tid), &attr, threads_startup_thread, &startup);
923 os::abort_errnum(result, "threads_impl_thread_start: pthread_create failed");
925 /* destroy the thread attributes */
927 result = pthread_attr_destroy(&attr);
930 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_destroy failed");
932 /* signal that pthread_create has returned, so thread->tid is valid */
934 threads_sem_post(&sem_first);
936 /* wait here until the thread has entered itself into the thread list */
938 threads_sem_wait(&sem);
943 sem_destroy(&sem_first);
947 /* threads_set_thread_priority *************************************************
949 Set the priority of the given thread.
952 tid..........thread id
953 priority.....priority to set
955 ******************************************************************************/
957 void threads_set_thread_priority(pthread_t tid, int priority)
959 struct sched_param schedp;
962 pthread_getschedparam(tid, &policy, &schedp);
963 schedp.sched_priority = priority;
964 pthread_setschedparam(tid, policy, &schedp);
969 * Detaches the current thread from the VM.
971 * @return true on success, false otherwise
973 bool thread_detach_current_thread(void)
975 threadobject* t = thread_get_current();
981 /* If the given thread has already been detached, this operation
984 if (thread_is_attached(t) == false)
987 DEBUGTHREADS("detaching", t);
989 java_handle_t* object = thread_get_object(t);
990 java_lang_Thread jlt(object);
992 #if defined(ENABLE_JAVASE)
993 java_handle_t* group = jlt.get_group();
995 /* If there's an uncaught exception, call uncaughtException on the
996 thread's exception handler, or the thread's group if this is
999 java_handle_t* e = exceptions_get_and_clear_exception();
1002 /* We use the type void* for handler here, as it's not trivial
1003 to build the java_lang_Thread_UncaughtExceptionHandler
1004 header file with cacaoh. */
1006 # if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
1008 java_handle_t* handler = jlt.get_exceptionHandler();
1010 # elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK)
1012 java_handle_t* handler = jlt.get_uncaughtExceptionHandler();
1019 if (handler != NULL) {
1020 LLNI_class_get(handler, c);
1021 h = (java_handle_t *) handler;
1024 LLNI_class_get(group, c);
1025 h = (java_handle_t *) group;
1028 methodinfo* m = class_resolveclassmethod(c,
1029 utf_uncaughtException,
1030 utf_java_lang_Thread_java_lang_Throwable__V,
1037 (void) vm_call_method(m, h, object, e);
1039 if (exceptions_get_exception())
1043 /* XXX TWISTI: should all threads be in a ThreadGroup? */
1045 /* Remove thread from the thread group. */
1047 if (group != NULL) {
1049 LLNI_class_get(group, c);
1051 # if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
1052 methodinfo* m = class_resolveclassmethod(c,
1054 utf_java_lang_Thread__V,
1055 class_java_lang_ThreadGroup,
1057 # elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK)
1058 methodinfo* m = class_resolveclassmethod(c,
1060 utf_java_lang_Thread__V,
1061 class_java_lang_ThreadGroup,
1064 # error unknown classpath configuration
1070 (void) vm_call_method(m, group, object);
1072 if (exceptions_get_exception())
1075 // Clear the ThreadGroup in the Java thread object (Mauve
1076 // test: gnu/testlet/java/lang/Thread/getThreadGroup).
1077 jlt.set_group(NULL);
1081 /* Thread has terminated. */
1083 thread_set_state_terminated(t);
1085 /* Notify all threads waiting on this thread. These are joining
1088 /* XXX Care about exceptions? */
1089 (void) lock_monitor_enter(jlt.get_handle());
1091 lock_notify_all_object(jlt.get_handle());
1093 /* XXX Care about exceptions? */
1094 (void) lock_monitor_exit(jlt.get_handle());
1096 /* Enter the join-mutex before calling thread_free, so
1097 threads_join_all_threads gets the correct number of non-daemon
1100 threads_mutex_join_lock();
1102 /* Free the internal thread data-structure. */
1106 /* Signal that this thread has finished and leave the mutex. */
1108 cond_join->signal();
1109 threads_mutex_join_unlock();
1115 /* threads_suspend_thread ******************************************************
1117 Suspend the passed thread. Execution stops until the thread
1118 is explicitly resumend again.
1121 reason.....Reason for suspending this thread.
1123 *******************************************************************************/
1125 bool threads_suspend_thread(threadobject *thread, s4 reason)
1127 /* acquire the suspendmutex */
1128 thread->suspendmutex->lock();
1130 if (thread->suspended) {
1131 thread->suspendmutex->unlock();
1135 /* set the reason for the suspension */
1136 thread->suspend_reason = reason;
1138 /* send the suspend signal to the thread */
1139 assert(thread != THREADOBJECT);
1140 if (pthread_kill(thread->tid, SIGUSR1) != 0)
1141 vm_abort("threads_suspend_thread: pthread_kill failed: %s",
1144 /* REMEMBER: do not release the suspendmutex, this is done
1145 by the thread itself in threads_suspend_ack(). */
1151 /* threads_suspend_ack *********************************************************
1153 Acknowledges the suspension of the current thread.
1156 pc.....The PC where the thread suspended its execution.
1157 sp.....The SP before the thread suspended its execution.
1159 *******************************************************************************/
1161 #if defined(ENABLE_GC_CACAO)
1162 void threads_suspend_ack(u1* pc, u1* sp)
1164 threadobject *thread;
1166 thread = THREADOBJECT;
1168 assert(thread->suspend_reason != 0);
1170 /* TODO: remember dump memory size */
1172 /* inform the GC about the suspension */
1173 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD && gc_pending) {
1175 /* check if the GC wants to leave the thread running */
1176 if (!gc_suspend(thread, pc, sp)) {
1178 /* REMEMBER: we do not unlock the suspendmutex because the thread
1179 will suspend itself again at a later time */
1185 /* mark this thread as suspended and remember the PC */
1187 thread->suspended = true;
1189 /* if we are stopping the world, we should send a global ack */
1190 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD) {
1191 threads_sem_post(&suspend_ack);
1194 DEBUGTHREADS("suspending", thread);
1196 /* release the suspension mutex and wait till we are resumed */
1197 thread->suspendcond->wait(thread->suspendmutex);
1199 DEBUGTHREADS("resuming", thread);
1201 /* if we are stopping the world, we should send a global ack */
1202 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD) {
1203 threads_sem_post(&suspend_ack);
1206 /* TODO: free dump memory */
1208 /* release the suspendmutex */
1209 thread->suspendmutex->unlock();
1214 /* threads_resume_thread *******************************************************
1216 Resumes the execution of the passed thread.
1218 *******************************************************************************/
1220 #if defined(ENABLE_GC_CACAO)
1221 bool threads_resume_thread(threadobject *thread)
1223 /* acquire the suspendmutex */
1224 thread->suspendmutex->lock();
1226 if (!thread->suspended) {
1227 thread->suspendmutex->unlock();
1231 thread->suspended = false;
1233 /* tell everyone that the thread should resume */
1234 assert(thread != THREADOBJECT);
1235 thread->suspendcond->broadcast();
1237 /* release the suspendmutex */
1238 thread->suspendmutex->unlock();
1245 /* threads_join_all_threads ****************************************************
1247 Join all non-daemon threads.
1249 *******************************************************************************/
1251 void threads_join_all_threads(void)
1255 /* get current thread */
1259 /* This thread is waiting for all non-daemon threads to exit. */
1261 thread_set_state_waiting(t);
1263 /* enter join mutex */
1265 threads_mutex_join_lock();
1267 /* Wait for condition as long as we have non-daemon threads. We
1268 compare against 1 because the current (main thread) is also a
1269 non-daemon thread. */
1271 while (ThreadList::get_number_of_non_daemon_threads() > 1)
1272 cond_join->wait(mutex_join);
1274 /* leave join mutex */
1276 threads_mutex_join_unlock();
1280 /* threads_timespec_earlier ****************************************************
1282 Return true if timespec tv1 is earlier than timespec tv2.
1285 tv1..........first timespec
1286 tv2..........second timespec
1289 true, if the first timespec is earlier
1291 *******************************************************************************/
1293 static inline bool threads_timespec_earlier(const struct timespec *tv1,
1294 const struct timespec *tv2)
1296 return (tv1->tv_sec < tv2->tv_sec)
1298 (tv1->tv_sec == tv2->tv_sec && tv1->tv_nsec < tv2->tv_nsec);
1302 /* threads_current_time_is_earlier_than ****************************************
1304 Check if the current time is earlier than the given timespec.
1307 tv...........the timespec to compare against
1310 true, if the current time is earlier
1312 *******************************************************************************/
1314 static bool threads_current_time_is_earlier_than(const struct timespec *tv)
1316 struct timeval tvnow;
1317 struct timespec tsnow;
1319 /* get current time */
1321 if (gettimeofday(&tvnow, NULL) != 0)
1322 vm_abort("gettimeofday failed: %s\n", strerror(errno));
1324 /* convert it to a timespec */
1326 tsnow.tv_sec = tvnow.tv_sec;
1327 tsnow.tv_nsec = tvnow.tv_usec * 1000;
1329 /* compare current time with the given timespec */
1331 return threads_timespec_earlier(&tsnow, tv);
1335 /* threads_wait_with_timeout ***************************************************
1337 Wait until the given point in time on a monitor until either
1338 we are notified, we are interrupted, or the time is up.
1341 t............the current thread
1342 wakeupTime...absolute (latest) wakeup time
1343 If both tv_sec and tv_nsec are zero, this function
1344 waits for an unlimited amount of time.
1346 *******************************************************************************/
1348 static void threads_wait_with_timeout(threadobject *t, struct timespec *wakeupTime, bool parking)
1350 // Acquire the waitmutex.
1351 t->waitmutex->lock();
1353 /* wait on waitcond */
1355 if (wakeupTime->tv_sec || wakeupTime->tv_nsec) {
1357 while (!t->interrupted && !(parking ? t->park_permit : t->signaled)
1358 && threads_current_time_is_earlier_than(wakeupTime))
1361 thread_set_state_timed_parked(t);
1363 thread_set_state_timed_waiting(t);
1365 t->waitcond->timedwait(t->waitmutex, wakeupTime);
1367 thread_set_state_runnable(t);
1372 while (!t->interrupted && !(parking ? t->park_permit : t->signaled)) {
1374 thread_set_state_parked(t);
1376 thread_set_state_waiting(t);
1378 t->waitcond->wait(t->waitmutex);
1380 thread_set_state_runnable(t);
1385 t->park_permit = false;
1387 // Release the waitmutex.
1388 t->waitmutex->unlock();
1392 /* threads_wait_with_timeout_relative ******************************************
1394 Wait for the given maximum amount of time on a monitor until either
1395 we are notified, we are interrupted, or the time is up.
1398 t............the current thread
1399 millis.......milliseconds to wait
1400 nanos........nanoseconds to wait
1402 *******************************************************************************/
1404 void threads_wait_with_timeout_relative(threadobject *thread, s8 millis,
1407 struct timespec wakeupTime;
1409 /* calculate the the (latest) wakeup time */
1411 threads_calc_absolute_time(&wakeupTime, millis, nanos);
1415 threads_wait_with_timeout(thread, &wakeupTime, false);
1419 /* threads_calc_absolute_time **************************************************
1421 Calculate the absolute point in time a given number of ms and ns from now.
1424 millis............milliseconds from now
1425 nanos.............nanoseconds from now
1428 *tm...............receives the timespec of the absolute point in time
1430 *******************************************************************************/
1432 static void threads_calc_absolute_time(struct timespec *tm, s8 millis, s4 nanos)
1434 // (at least with GNU classpath) we know that 0 <= nanos <= 999999
1436 if (!millis && !nanos)
1439 gettimeofday(&tv, NULL);
1440 s8 secs = tv.tv_sec + millis / 1000;
1441 if (secs > INT32_MAX) // integer overflow
1445 long nsec = tv.tv_usec * 1000 + (s4) millis * 1000000 + nanos;
1446 tm->tv_sec = tv.tv_sec + nsec / 1000000000;
1447 if (tm->tv_sec < tv.tv_sec) // integer overflow
1449 tm->tv_nsec = nsec % 1000000000;
1457 /* threads_thread_interrupt ****************************************************
1459 Interrupt the given thread.
1461 The thread gets the "waitcond" signal and
1462 its interrupted flag is set to true.
1465 thread............the thread to interrupt
1467 *******************************************************************************/
1469 void threads_thread_interrupt(threadobject *t)
1471 /* Signal the thread a "waitcond" and tell it that it has been
1474 t->waitmutex->lock();
1476 DEBUGTHREADS("interrupted", t);
1478 /* Interrupt blocking system call using a signal. */
1480 pthread_kill(t->tid, Signal_INTERRUPT_SYSTEM_CALL);
1482 t->waitcond->signal();
1484 t->interrupted = true;
1486 t->waitmutex->unlock();
1491 * Sleep the current thread for the specified amount of time.
1493 * @param millis Milliseconds to sleep.
1494 * @param nanos Nanoseconds to sleep.
1496 void threads_sleep(int64_t millis, int32_t nanos)
1499 struct timespec wakeupTime;
1503 /* exceptions_throw_illegalargumentexception("timeout value is negative"); */
1504 exceptions_throw_illegalargumentexception();
1508 t = thread_get_current();
1510 if (thread_is_interrupted(t) && !exceptions_get_exception()) {
1511 /* Clear interrupted flag (Mauve test:
1512 gnu/testlet/java/lang/Thread/interrupt). */
1514 thread_set_interrupted(t, false);
1516 /* exceptions_throw_interruptedexception("sleep interrupted"); */
1517 exceptions_throw_interruptedexception();
1521 // (Note taken from classpath/vm/reference/java/lang/VMThread.java (sleep))
1522 // Note: JDK treats a zero length sleep is like Thread.yield(),
1523 // without checking the interrupted status of the thread. It's
1524 // unclear if this is a bug in the implementation or the spec.
1525 // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6213203 */
1526 if (millis == 0 && nanos == 0) {
1530 threads_calc_absolute_time(&wakeupTime, millis, nanos);
1532 threads_wait_with_timeout(t, &wakeupTime, false);
1534 interrupted = thread_is_interrupted(t);
1537 thread_set_interrupted(t, false);
1539 // An other exception could have been thrown
1540 // (e.g. ThreadDeathException).
1541 if (!exceptions_get_exception())
1542 exceptions_throw_interruptedexception();
1548 * Park the current thread for the specified amount of time or until a
1549 * specified deadline.
1551 * @param absolute Is the time in nanos a deadline or a duration?
1552 * @param nanos Nanoseconds to park (absolute=false)
1553 * or deadline in milliseconds (absolute=true)
1555 void threads_park(bool absolute, int64_t nanos)
1558 struct timespec wakeupTime;
1560 t = thread_get_current();
1563 wakeupTime.tv_nsec = 0;
1564 wakeupTime.tv_sec = nanos / 1000; /* milliseconds */
1567 threads_calc_absolute_time(&wakeupTime, nanos / 1000000, nanos % 1000000);
1569 threads_wait_with_timeout(t, &wakeupTime, true);
1573 * Unpark the specified thread.
1575 * @param t The thread to unpark.
1577 void threads_unpark(threadobject *t)
1579 t->waitmutex->lock();
1581 t->waitcond->signal();
1583 t->park_permit = true;
1585 t->waitmutex->unlock();
1589 /* threads_yield ***************************************************************
1591 Yield to the scheduler.
1593 *******************************************************************************/
1595 void threads_yield(void)
1600 #if defined(ENABLE_TLH)
1602 void threads_tlh_add_frame() {
1603 tlh_add_frame(&(THREADOBJECT->tlh));
1606 void threads_tlh_remove_frame() {
1607 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: