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/hook.hpp"
70 #include "vm/javaobjects.hpp"
71 #include "vm/options.h"
73 #include "vm/signallocal.hpp"
74 #include "vm/string.hpp"
77 #if defined(ENABLE_STATISTICS)
78 # include "vm/statistics.h"
81 #include "vm/jit/asmpart.h"
83 #if !defined(__DARWIN__)
84 # include <semaphore.h>
87 #if defined(__LINUX__)
88 # define GC_LINUX_THREADS
89 #elif defined(__IRIX__)
90 # define GC_IRIX_THREADS
91 #elif defined(__DARWIN__)
92 # define GC_DARWIN_THREADS
95 #if defined(ENABLE_GC_BOEHM)
96 /* We need to include Boehm's gc.h here because it overrides
97 pthread_create and friends. */
98 # include "mm/boehm-gc/include/gc.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 os::abort_errnum(result, "threads_impl_thread_free: pthread_cond_destroy failed");
552 result = pthread_cond_destroy(&(t->waitcond));
555 os::abort_errnum(result, "threads_impl_thread_free: pthread_cond_destroy failed");
557 delete t->suspendmutex;
559 result = pthread_cond_destroy(&(t->suspendcond));
562 os::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 os::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 os::abort_errnum(result, "threads_impl_init: pthread_attr_init failed");
674 result = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
677 os::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 // Hook point just before the threads initial method is executed.
796 Hook::thread_start(t);
798 DEBUGTHREADS("starting", t);
800 /* find and run the Thread.run()V method if no other function was passed */
802 if (function == NULL) {
803 #if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
804 /* We need to start the run method of
805 java.lang.VMThread. Since this is a final class, we can use
806 the class object directly. */
808 c = class_java_lang_VMThread;
809 #elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK) || defined(WITH_JAVA_RUNTIME_LIBRARY_CLDC1_1)
810 LLNI_class_get(object, c);
812 # error unknown classpath configuration
815 m = class_resolveclassmethod(c, utf_run, utf_void__void, c, true);
818 vm_abort("threads_startup_thread: run() method not found in class");
820 #if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
822 // We need to start the run method of java.lang.VMThread.
823 java_lang_VMThread jlvmt(jlt.get_vmThread());
824 java_handle_t* h = jlvmt.get_handle();
826 #elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK) || defined(WITH_JAVA_RUNTIME_LIBRARY_CLDC1_1)
828 java_handle_t* h = jlt.get_handle();
831 # error unknown classpath configuration
834 /* Run the thread. */
836 (void) vm_call_method(m, h);
839 /* call passed function, e.g. finalizer_thread */
844 DEBUGTHREADS("stopping", t);
846 // Hook point just after the threads initial method returned.
849 /* We ignore the return value. */
851 (void) thread_detach_current_thread();
857 /* threads_impl_thread_start ***************************************************
859 Start a thread in the JVM. Both (vm internal and java) thread
863 thread....the thread object
864 f.........function to run in the new thread. NULL means that the
865 "run" method of the object `t` should be called
867 ******************************************************************************/
869 void threads_impl_thread_start(threadobject *thread, functionptr f)
877 /* fill startupinfo structure passed by pthread_create to
878 * threads_startup_thread */
880 startup.thread = thread;
881 startup.function = f; /* maybe we don't call Thread.run()V */
883 startup.psem_first = &sem_first;
885 threads_sem_init(&sem, 0, 0);
886 threads_sem_init(&sem_first, 0, 0);
888 /* Initialize thread attributes. */
890 result = pthread_attr_init(&attr);
893 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_init failed");
895 result = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
898 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_setdetachstate failed");
900 /* initialize thread stacksize */
902 result = pthread_attr_setstacksize(&attr, opt_stacksize);
905 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_setstacksize failed");
907 /* create the thread */
909 result = pthread_create(&(thread->tid), &attr, threads_startup_thread, &startup);
912 os::abort_errnum(result, "threads_impl_thread_start: pthread_create failed");
914 /* destroy the thread attributes */
916 result = pthread_attr_destroy(&attr);
919 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_destroy failed");
921 /* signal that pthread_create has returned, so thread->tid is valid */
923 threads_sem_post(&sem_first);
925 /* wait here until the thread has entered itself into the thread list */
927 threads_sem_wait(&sem);
932 sem_destroy(&sem_first);
936 /* threads_set_thread_priority *************************************************
938 Set the priority of the given thread.
941 tid..........thread id
942 priority.....priority to set
944 ******************************************************************************/
946 void threads_set_thread_priority(pthread_t tid, int priority)
948 struct sched_param schedp;
951 pthread_getschedparam(tid, &policy, &schedp);
952 schedp.sched_priority = priority;
953 pthread_setschedparam(tid, policy, &schedp);
958 * Detaches the current thread from the VM.
960 * @return true on success, false otherwise
962 bool thread_detach_current_thread(void)
964 threadobject* t = thread_get_current();
970 /* If the given thread has already been detached, this operation
973 if (thread_is_attached(t) == false)
976 DEBUGTHREADS("detaching", t);
978 java_handle_t* object = thread_get_object(t);
979 java_lang_Thread jlt(object);
981 #if defined(ENABLE_JAVASE)
982 java_handle_t* group = jlt.get_group();
984 /* If there's an uncaught exception, call uncaughtException on the
985 thread's exception handler, or the thread's group if this is
988 java_handle_t* e = exceptions_get_and_clear_exception();
991 /* We use the type void* for handler here, as it's not trivial
992 to build the java_lang_Thread_UncaughtExceptionHandler
993 header file with cacaoh. */
995 # if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
997 java_handle_t* handler = jlt.get_exceptionHandler();
999 # elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK)
1001 java_handle_t* handler = jlt.get_uncaughtExceptionHandler();
1008 if (handler != NULL) {
1009 LLNI_class_get(handler, c);
1010 h = (java_handle_t *) handler;
1013 LLNI_class_get(group, c);
1014 h = (java_handle_t *) group;
1017 methodinfo* m = class_resolveclassmethod(c,
1018 utf_uncaughtException,
1019 utf_java_lang_Thread_java_lang_Throwable__V,
1026 (void) vm_call_method(m, h, object, e);
1028 if (exceptions_get_exception())
1032 /* XXX TWISTI: should all threads be in a ThreadGroup? */
1034 /* Remove thread from the thread group. */
1036 if (group != NULL) {
1038 LLNI_class_get(group, c);
1040 # if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
1041 methodinfo* m = class_resolveclassmethod(c,
1043 utf_java_lang_Thread__V,
1044 class_java_lang_ThreadGroup,
1046 # elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK)
1047 methodinfo* m = class_resolveclassmethod(c,
1049 utf_java_lang_Thread__V,
1050 class_java_lang_ThreadGroup,
1053 # error unknown classpath configuration
1059 (void) vm_call_method(m, group, object);
1061 if (exceptions_get_exception())
1064 // Clear the ThreadGroup in the Java thread object (Mauve
1065 // test: gnu/testlet/java/lang/Thread/getThreadGroup).
1066 jlt.set_group(NULL);
1070 /* Thread has terminated. */
1072 thread_set_state_terminated(t);
1074 /* Notify all threads waiting on this thread. These are joining
1077 /* XXX Care about exceptions? */
1078 (void) lock_monitor_enter(jlt.get_handle());
1080 lock_notify_all_object(jlt.get_handle());
1082 /* XXX Care about exceptions? */
1083 (void) lock_monitor_exit(jlt.get_handle());
1085 /* Enter the join-mutex before calling thread_free, so
1086 threads_join_all_threads gets the correct number of non-daemon
1089 threads_mutex_join_lock();
1091 /* Free the internal thread data-structure. */
1095 /* Signal that this thread has finished and leave the mutex. */
1097 cond_join->signal();
1098 threads_mutex_join_unlock();
1104 /* threads_suspend_thread ******************************************************
1106 Suspend the passed thread. Execution stops until the thread
1107 is explicitly resumend again.
1110 reason.....Reason for suspending this thread.
1112 *******************************************************************************/
1114 bool threads_suspend_thread(threadobject *thread, s4 reason)
1116 /* acquire the suspendmutex */
1117 thread->suspendmutex->lock();
1119 if (thread->suspended) {
1120 thread->suspendmutex->unlock();
1124 /* set the reason for the suspension */
1125 thread->suspend_reason = reason;
1127 /* send the suspend signal to the thread */
1128 assert(thread != THREADOBJECT);
1129 if (pthread_kill(thread->tid, SIGUSR1) != 0)
1130 vm_abort("threads_suspend_thread: pthread_kill failed: %s",
1133 /* REMEMBER: do not release the suspendmutex, this is done
1134 by the thread itself in threads_suspend_ack(). */
1140 /* threads_suspend_ack *********************************************************
1142 Acknowledges the suspension of the current thread.
1145 pc.....The PC where the thread suspended its execution.
1146 sp.....The SP before the thread suspended its execution.
1148 *******************************************************************************/
1150 #if defined(ENABLE_GC_CACAO)
1151 void threads_suspend_ack(u1* pc, u1* sp)
1153 threadobject *thread;
1155 thread = THREADOBJECT;
1157 assert(thread->suspend_reason != 0);
1159 /* TODO: remember dump memory size */
1161 /* inform the GC about the suspension */
1162 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD && gc_pending) {
1164 /* check if the GC wants to leave the thread running */
1165 if (!gc_suspend(thread, pc, sp)) {
1167 /* REMEMBER: we do not unlock the suspendmutex because the thread
1168 will suspend itself again at a later time */
1174 /* mark this thread as suspended and remember the PC */
1176 thread->suspended = true;
1178 /* if we are stopping the world, we should send a global ack */
1179 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD) {
1180 threads_sem_post(&suspend_ack);
1183 DEBUGTHREADS("suspending", thread);
1185 /* release the suspension mutex and wait till we are resumed */
1186 thread->suspendcond->wait(thread->suspendmutex);
1188 DEBUGTHREADS("resuming", thread);
1190 /* if we are stopping the world, we should send a global ack */
1191 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD) {
1192 threads_sem_post(&suspend_ack);
1195 /* TODO: free dump memory */
1197 /* release the suspendmutex */
1198 thread->suspendmutex->unlock();
1203 /* threads_resume_thread *******************************************************
1205 Resumes the execution of the passed thread.
1207 *******************************************************************************/
1209 #if defined(ENABLE_GC_CACAO)
1210 bool threads_resume_thread(threadobject *thread)
1212 /* acquire the suspendmutex */
1213 thread->suspendmutex->lock();
1215 if (!thread->suspended) {
1216 thread->suspendmutex->unlock();
1220 thread->suspended = false;
1222 /* tell everyone that the thread should resume */
1223 assert(thread != THREADOBJECT);
1224 thread->suspendcond->broadcast();
1226 /* release the suspendmutex */
1227 thread->suspendmutex->unlock();
1234 /* threads_join_all_threads ****************************************************
1236 Join all non-daemon threads.
1238 *******************************************************************************/
1240 void threads_join_all_threads(void)
1244 /* get current thread */
1248 /* This thread is waiting for all non-daemon threads to exit. */
1250 thread_set_state_waiting(t);
1252 /* enter join mutex */
1254 threads_mutex_join_lock();
1256 /* Wait for condition as long as we have non-daemon threads. We
1257 compare against 1 because the current (main thread) is also a
1258 non-daemon thread. */
1260 while (ThreadList::get_number_of_non_daemon_threads() > 1)
1261 cond_join->wait(mutex_join);
1263 /* leave join mutex */
1265 threads_mutex_join_unlock();
1269 /* threads_timespec_earlier ****************************************************
1271 Return true if timespec tv1 is earlier than timespec tv2.
1274 tv1..........first timespec
1275 tv2..........second timespec
1278 true, if the first timespec is earlier
1280 *******************************************************************************/
1282 static inline bool threads_timespec_earlier(const struct timespec *tv1,
1283 const struct timespec *tv2)
1285 return (tv1->tv_sec < tv2->tv_sec)
1287 (tv1->tv_sec == tv2->tv_sec && tv1->tv_nsec < tv2->tv_nsec);
1291 /* threads_current_time_is_earlier_than ****************************************
1293 Check if the current time is earlier than the given timespec.
1296 tv...........the timespec to compare against
1299 true, if the current time is earlier
1301 *******************************************************************************/
1303 static bool threads_current_time_is_earlier_than(const struct timespec *tv)
1305 struct timeval tvnow;
1306 struct timespec tsnow;
1308 /* get current time */
1310 if (gettimeofday(&tvnow, NULL) != 0)
1311 vm_abort("gettimeofday failed: %s\n", strerror(errno));
1313 /* convert it to a timespec */
1315 tsnow.tv_sec = tvnow.tv_sec;
1316 tsnow.tv_nsec = tvnow.tv_usec * 1000;
1318 /* compare current time with the given timespec */
1320 return threads_timespec_earlier(&tsnow, tv);
1324 /* threads_wait_with_timeout ***************************************************
1326 Wait until the given point in time on a monitor until either
1327 we are notified, we are interrupted, or the time is up.
1330 t............the current thread
1331 wakeupTime...absolute (latest) wakeup time
1332 If both tv_sec and tv_nsec are zero, this function
1333 waits for an unlimited amount of time.
1335 *******************************************************************************/
1337 static void threads_wait_with_timeout(threadobject *t, struct timespec *wakeupTime, bool parking)
1339 // Acquire the waitmutex.
1340 t->waitmutex->lock();
1342 /* wait on waitcond */
1344 if (wakeupTime->tv_sec || wakeupTime->tv_nsec) {
1346 while (!t->interrupted && !(parking ? t->park_permit : t->signaled)
1347 && threads_current_time_is_earlier_than(wakeupTime))
1350 thread_set_state_timed_parked(t);
1352 thread_set_state_timed_waiting(t);
1354 t->waitcond->timedwait(t->waitmutex, wakeupTime);
1356 thread_set_state_runnable(t);
1361 while (!t->interrupted && !(parking ? t->park_permit : t->signaled)) {
1363 thread_set_state_parked(t);
1365 thread_set_state_waiting(t);
1367 t->waitcond->wait(t->waitmutex);
1369 thread_set_state_runnable(t);
1374 t->park_permit = false;
1376 // Release the waitmutex.
1377 t->waitmutex->unlock();
1381 /* threads_wait_with_timeout_relative ******************************************
1383 Wait for the given maximum amount of time on a monitor until either
1384 we are notified, we are interrupted, or the time is up.
1387 t............the current thread
1388 millis.......milliseconds to wait
1389 nanos........nanoseconds to wait
1391 *******************************************************************************/
1393 void threads_wait_with_timeout_relative(threadobject *thread, s8 millis,
1396 struct timespec wakeupTime;
1398 /* calculate the the (latest) wakeup time */
1400 threads_calc_absolute_time(&wakeupTime, millis, nanos);
1404 threads_wait_with_timeout(thread, &wakeupTime, false);
1408 /* threads_calc_absolute_time **************************************************
1410 Calculate the absolute point in time a given number of ms and ns from now.
1413 millis............milliseconds from now
1414 nanos.............nanoseconds from now
1417 *tm...............receives the timespec of the absolute point in time
1419 *******************************************************************************/
1421 static void threads_calc_absolute_time(struct timespec *tm, s8 millis, s4 nanos)
1423 // (at least with GNU classpath) we know that 0 <= nanos <= 999999
1425 if (!millis && !nanos)
1428 gettimeofday(&tv, NULL);
1429 s8 secs = tv.tv_sec + millis / 1000;
1430 if (secs > INT32_MAX) // integer overflow
1434 long nsec = tv.tv_usec * 1000 + (s4) millis * 1000000 + nanos;
1435 tm->tv_sec = tv.tv_sec + nsec / 1000000000;
1436 if (tm->tv_sec < tv.tv_sec) // integer overflow
1438 tm->tv_nsec = nsec % 1000000000;
1446 /* threads_thread_interrupt ****************************************************
1448 Interrupt the given thread.
1450 The thread gets the "waitcond" signal and
1451 its interrupted flag is set to true.
1454 thread............the thread to interrupt
1456 *******************************************************************************/
1458 void threads_thread_interrupt(threadobject *t)
1460 /* Signal the thread a "waitcond" and tell it that it has been
1463 t->waitmutex->lock();
1465 DEBUGTHREADS("interrupted", t);
1467 /* Interrupt blocking system call using a signal. */
1469 pthread_kill(t->tid, Signal_INTERRUPT_SYSTEM_CALL);
1471 t->waitcond->signal();
1473 t->interrupted = true;
1475 t->waitmutex->unlock();
1480 * Sleep the current thread for the specified amount of time.
1482 * @param millis Milliseconds to sleep.
1483 * @param nanos Nanoseconds to sleep.
1485 void threads_sleep(int64_t millis, int32_t nanos)
1488 struct timespec wakeupTime;
1492 /* exceptions_throw_illegalargumentexception("timeout value is negative"); */
1493 exceptions_throw_illegalargumentexception();
1497 t = thread_get_current();
1499 if (thread_is_interrupted(t) && !exceptions_get_exception()) {
1500 /* Clear interrupted flag (Mauve test:
1501 gnu/testlet/java/lang/Thread/interrupt). */
1503 thread_set_interrupted(t, false);
1505 /* exceptions_throw_interruptedexception("sleep interrupted"); */
1506 exceptions_throw_interruptedexception();
1510 // (Note taken from classpath/vm/reference/java/lang/VMThread.java (sleep))
1511 // Note: JDK treats a zero length sleep is like Thread.yield(),
1512 // without checking the interrupted status of the thread. It's
1513 // unclear if this is a bug in the implementation or the spec.
1514 // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6213203 */
1515 if (millis == 0 && nanos == 0) {
1519 threads_calc_absolute_time(&wakeupTime, millis, nanos);
1521 threads_wait_with_timeout(t, &wakeupTime, false);
1523 interrupted = thread_is_interrupted(t);
1526 thread_set_interrupted(t, false);
1528 // An other exception could have been thrown
1529 // (e.g. ThreadDeathException).
1530 if (!exceptions_get_exception())
1531 exceptions_throw_interruptedexception();
1537 * Park the current thread for the specified amount of time or until a
1538 * specified deadline.
1540 * @param absolute Is the time in nanos a deadline or a duration?
1541 * @param nanos Nanoseconds to park (absolute=false)
1542 * or deadline in milliseconds (absolute=true)
1544 void threads_park(bool absolute, int64_t nanos)
1547 struct timespec wakeupTime;
1549 t = thread_get_current();
1552 wakeupTime.tv_nsec = 0;
1553 wakeupTime.tv_sec = nanos / 1000; /* milliseconds */
1556 threads_calc_absolute_time(&wakeupTime, nanos / 1000000, nanos % 1000000);
1558 threads_wait_with_timeout(t, &wakeupTime, true);
1562 * Unpark the specified thread.
1564 * @param t The thread to unpark.
1566 void threads_unpark(threadobject *t)
1568 t->waitmutex->lock();
1570 t->waitcond->signal();
1572 t->park_permit = true;
1574 t->waitmutex->unlock();
1578 /* threads_yield ***************************************************************
1580 Yield to the scheduler.
1582 *******************************************************************************/
1584 void threads_yield(void)
1589 #if defined(ENABLE_TLH)
1591 void threads_tlh_add_frame() {
1592 tlh_add_frame(&(THREADOBJECT->tlh));
1595 void threads_tlh_remove_frame() {
1596 tlh_remove_frame(&(THREADOBJECT->tlh));
1603 * These are local overrides for various environment variables in Emacs.
1604 * Please do not remove this and leave it at the end of the file, where
1605 * Emacs will automagically detect them.
1606 * ---------------------------------------------------------------------
1609 * indent-tabs-mode: t
1613 * vim:noexpandtab:sw=4:ts=4: