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__)
92 # include <semaphore.h>
95 #if defined(__LINUX__)
96 # define GC_LINUX_THREADS
97 #elif defined(__IRIX__)
98 # define GC_IRIX_THREADS
99 #elif defined(__DARWIN__)
100 # define GC_DARWIN_THREADS
103 #if defined(ENABLE_GC_BOEHM)
104 /* We need to include Boehm's gc.h here because it overrides
105 pthread_create and friends. */
106 # include "mm/boehm-gc/include/gc.h"
110 #if defined(__DARWIN__)
111 /* Darwin has no working semaphore implementation. This one is taken
115 This is a very simple semaphore implementation for Darwin. It
116 is implemented in terms of pthreads calls so it isn't async signal
117 safe. This isn't a problem because signals aren't used to
118 suspend threads on Darwin.
121 static int sem_init(sem_t *sem, int pshared, int value)
126 sem->mutex = new Mutex();
127 sem->cond = new Condition();
133 static int sem_post(sem_t *sem)
138 sem->mutex->unlock();
143 static int sem_wait(sem_t *sem)
147 while (sem->value == 0) {
148 sem->cond->wait(sem->mutex);
152 sem->mutex->unlock();
157 static int sem_destroy(sem_t *sem)
164 #endif /* defined(__DARWIN__) */
167 /* startupinfo *****************************************************************
169 Struct used to pass info from threads_start_thread to
170 threads_startup_thread.
172 ******************************************************************************/
175 threadobject *thread; /* threadobject for this thread */
176 functionptr function; /* function to run in the new thread */
177 sem_t *psem; /* signals when thread has been entered */
178 /* in the thread list */
179 sem_t *psem_first; /* signals when pthread_create has returned */
183 /* prototypes *****************************************************************/
185 static void threads_calc_absolute_time(struct timespec *tm, s8 millis, s4 nanos);
188 /******************************************************************************/
189 /* GLOBAL VARIABLES */
190 /******************************************************************************/
192 /* the thread object of the current thread */
193 /* This is either a thread-local variable defined with __thread, or */
194 /* a thread-specific value stored with key threads_current_threadobject_key. */
195 #if defined(HAVE___THREAD)
196 __thread threadobject *thread_current;
198 pthread_key_t thread_current_key;
201 /* global mutex for stop-the-world */
202 static Mutex* stopworldlock;
204 #if defined(ENABLE_GC_CACAO)
205 /* global mutex for the GC */
206 static Mutex* mutex_gc;
209 /* global mutex and condition for joining threads on exit */
210 static Mutex* mutex_join;
211 static Condition* cond_join;
213 #if defined(ENABLE_GC_CACAO)
214 /* semaphore used for acknowleding thread suspension */
215 static sem_t suspend_ack;
219 /* threads_sem_init ************************************************************
221 Initialize a semaphore. Checks against errors and interruptions.
224 sem..............the semaphore to initialize
225 shared...........true if this semaphore will be shared between processes
226 value............the initial value for the semaphore
228 *******************************************************************************/
230 void threads_sem_init(sem_t *sem, bool shared, int value)
237 r = sem_init(sem, shared, value);
240 } while (errno == EINTR);
242 vm_abort("sem_init failed: %s", strerror(errno));
246 /* threads_sem_wait ************************************************************
248 Wait for a semaphore, non-interruptible.
250 IMPORTANT: Always use this function instead of `sem_wait` directly, as
251 `sem_wait` may be interrupted by signals!
254 sem..............the semaphore to wait on
256 *******************************************************************************/
258 void threads_sem_wait(sem_t *sem)
268 } while (errno == EINTR);
270 vm_abort("sem_wait failed: %s", strerror(errno));
274 /* threads_sem_post ************************************************************
276 Increase the count of a semaphore. Checks for errors.
279 sem..............the semaphore to increase the count of
281 *******************************************************************************/
283 void threads_sem_post(sem_t *sem)
289 /* unlike sem_wait, sem_post is not interruptible */
295 vm_abort("sem_post failed: %s", strerror(errno));
299 /* threads_stopworld ***********************************************************
301 Stops the world from turning. All threads except the calling one
302 are suspended. The function returns as soon as all threads have
303 acknowledged their suspension.
305 *******************************************************************************/
307 #if defined(ENABLE_GC_CACAO)
308 void threads_stopworld(void)
310 #if !defined(__DARWIN__) && !defined(__CYGWIN__)
317 stopworldlock->lock();
319 /* lock the threads lists */
323 #if defined(__DARWIN__)
324 /*threads_cast_darwinstop();*/
326 #elif defined(__CYGWIN__)
332 DEBUGTHREADS("stops World", self);
336 /* suspend all running threads */
337 for (t = threadlist_first(); t != NULL; t = threadlist_next(t)) {
338 /* don't send the signal to ourself */
343 /* don't send the signal to NEW threads (because they are not
344 completely initialized) */
346 if (t->state == THREAD_STATE_NEW)
349 /* send the signal */
351 result = threads_suspend_thread(t, SUSPEND_REASON_STOPWORLD);
354 /* increase threads count */
359 /* wait for all threads signaled to suspend */
360 for (i = 0; i < count; i++)
361 threads_sem_wait(&suspend_ack);
364 /* ATTENTION: Don't unlock the threads-lists here so that
365 non-signaled NEW threads can't change their state and execute
371 /* threads_startworld **********************************************************
373 Starts the world again after it has previously been stopped.
375 *******************************************************************************/
377 #if defined(ENABLE_GC_CACAO)
378 void threads_startworld(void)
380 #if !defined(__DARWIN__) && !defined(__CYGWIN__)
387 #if defined(__DARWIN__)
388 /*threads_cast_darwinresume();*/
390 #elif defined(__IRIX__)
391 threads_cast_irixresume();
392 #elif defined(__CYGWIN__)
398 DEBUGTHREADS("starts World", self);
402 /* resume all thread we haltet */
403 for (t = threadlist_first(); t != NULL; t = threadlist_next(t)) {
404 /* don't send the signal to ourself */
409 /* don't send the signal to NEW threads (because they are not
410 completely initialized) */
412 if (t->state == THREAD_STATE_NEW)
415 /* send the signal */
417 result = threads_resume_thread(t);
420 /* increase threads count */
425 /* wait for all threads signaled to suspend */
426 for (i = 0; i < count; i++)
427 threads_sem_wait(&suspend_ack);
431 /* unlock the threads lists */
435 stopworldlock->unlock();
440 /* threads_impl_thread_clear ***************************************************
442 Clears all fields in threadobject the way an MZERO would have
443 done. MZERO cannot be used anymore because it would mess up the
447 t....the threadobject
449 *******************************************************************************/
451 void threads_impl_thread_clear(threadobject *t)
463 #if defined(__DARWIN__)
467 t->interrupted = false;
470 t->suspended = false;
471 t->suspend_reason = 0;
475 t->_exceptionptr = NULL;
476 t->_stackframeinfo = NULL;
477 t->_localref_table = NULL;
479 #if defined(ENABLE_INTRP)
480 t->_global_sp = NULL;
483 #if defined(ENABLE_GC_CACAO)
484 t->gc_critical = false;
490 // Simply reuse the existing dump memory.
493 /* threads_impl_thread_reuse ***************************************************
495 Resets some implementation fields in threadobject. This was
496 previously done in threads_impl_thread_new.
499 t....the threadobject
501 *******************************************************************************/
503 void threads_impl_thread_reuse(threadobject *t)
505 /* get the pthread id */
507 t->tid = pthread_self();
509 #if defined(ENABLE_DEBUG_FILTER)
510 /* Initialize filter counters */
511 t->filterverbosecallctr[0] = 0;
512 t->filterverbosecallctr[1] = 0;
516 t->tracejavacallindent = 0;
517 t->tracejavacallcount = 0;
524 /* not really needed */
525 t->flc_object = NULL;
527 #if defined(ENABLE_TLH)
528 tlh_destroy(&(t->tlh));
534 /* threads_impl_thread_free ****************************************************
536 Cleanup thread stuff.
539 t....the threadobject
541 *******************************************************************************/
545 void threads_impl_thread_free(threadobject *t)
549 /* Destroy the mutex and the condition. */
553 result = pthread_cond_destroy(&(t->flc_cond));
556 os::abort_errnum(result, "threads_impl_thread_free: pthread_cond_destroy failed");
560 result = pthread_cond_destroy(&(t->waitcond));
563 os::abort_errnum(result, "threads_impl_thread_free: pthread_cond_destroy failed");
565 delete t->suspendmutex;
567 result = pthread_cond_destroy(&(t->suspendcond));
570 os::abort_errnum(result, "threads_impl_thread_free: pthread_cond_destroy failed");
575 /* threads_impl_preinit ********************************************************
577 Do some early initialization of stuff required.
579 ATTENTION: Do NOT use any Java heap allocation here, as gc_init()
580 is called AFTER this function!
582 *******************************************************************************/
584 void threads_impl_preinit(void)
588 stopworldlock = new Mutex();
590 /* initialize exit mutex and condition (on exit we join all
593 mutex_join = new Mutex();
594 cond_join = new Condition();
596 #if defined(ENABLE_GC_CACAO)
597 /* initialize the GC mutex & suspend semaphore */
599 mutex_gc = new Mutex();
600 threads_sem_init(&suspend_ack, 0, 0);
603 #if !defined(HAVE___THREAD)
604 result = pthread_key_create(&thread_current_key, NULL);
606 os::abort_errnum(result, "threads_impl_preinit: pthread_key_create failed");
611 /* threads_mutex_gc_lock *******************************************************
613 Enter the global GC mutex.
615 *******************************************************************************/
617 #if defined(ENABLE_GC_CACAO)
618 void threads_mutex_gc_lock(void)
625 /* threads_mutex_gc_unlock *****************************************************
627 Leave the global GC mutex.
629 *******************************************************************************/
631 #if defined(ENABLE_GC_CACAO)
632 void threads_mutex_gc_unlock(void)
638 /* threads_mutex_join_lock *****************************************************
640 Enter the join mutex.
642 *******************************************************************************/
644 void threads_mutex_join_lock(void)
650 /* threads_mutex_join_unlock ***************************************************
652 Leave the join mutex.
654 *******************************************************************************/
656 void threads_mutex_join_unlock(void)
658 mutex_join->unlock();
662 /* threads_impl_init ***********************************************************
664 Initializes the implementation specific bits.
666 *******************************************************************************/
668 void threads_impl_init(void)
673 threads_set_thread_priority(pthread_self(), NORM_PRIORITY);
675 /* Initialize the thread attribute object. */
677 result = pthread_attr_init(&attr);
680 os::abort_errnum(result, "threads_impl_init: pthread_attr_init failed");
682 result = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
685 os::abort_errnum(result, "threads_impl_init: pthread_attr_setdetachstate failed");
689 /* threads_startup_thread ******************************************************
691 Thread startup function called by pthread_create.
693 Thread which have a startup.function != NULL are marked as internal
694 threads. All other threads are threated as normal Java threads.
696 NOTE: This function is not called directly by pthread_create. The Boehm GC
697 inserts its own GC_start_routine in between, which then calls
701 arg..........the argument passed to pthread_create, ie. a pointer to
702 a startupinfo struct. CAUTION: When the `psem` semaphore
703 is posted, the startupinfo struct becomes invalid! (It
704 is allocated on the stack of threads_start_thread.)
706 ******************************************************************************/
708 static void *threads_startup_thread(void *arg)
710 startupinfo *startup;
715 functionptr function;
717 #if defined(ENABLE_GC_BOEHM)
718 # if !defined(__DARWIN__)
719 struct GC_stack_base sb;
724 #if defined(ENABLE_INTRP)
725 u1 *intrp_thread_stack;
728 #if defined(ENABLE_INTRP)
729 /* create interpreter stack */
732 intrp_thread_stack = GCMNEW(u1, opt_stacksize);
733 MSET(intrp_thread_stack, 0, u1, opt_stacksize);
736 intrp_thread_stack = NULL;
739 /* get passed startupinfo structure and the values in there */
741 startup = (startupinfo*) arg;
744 function = startup->function;
745 psem = startup->psem;
747 /* Seems like we've encountered a situation where thread->tid was
748 not set by pthread_create. We alleviate this problem by waiting
749 for pthread_create to return. */
751 threads_sem_wait(startup->psem_first);
753 #if defined(__DARWIN__)
754 t->mach_thread = mach_thread_self();
757 /* Now that we are in the new thread, we can store the internal
758 thread data-structure in the TSD. */
760 thread_set_current(t);
762 #if defined(ENABLE_GC_BOEHM)
763 # if defined(__DARWIN__)
764 // This is currently not implemented in Boehm-GC. Just fail silently.
766 /* Register the thread with Boehm-GC. This must happen before the
767 thread allocates any memory from the GC heap.*/
769 result = GC_get_stack_base(&sb);
772 vm_abort("threads_startup_thread: GC_get_stack_base failed: result=%d", result);
774 GC_register_my_thread(&sb);
778 // Get the java.lang.Thread object for this thread.
779 java_handle_t* object = thread_get_object(t);
780 java_lang_Thread jlt(object);
782 /* set our priority */
784 threads_set_thread_priority(t->tid, jlt.get_priority());
786 /* Thread is completely initialized. */
788 thread_set_state_runnable(t);
790 /* tell threads_startup_thread that we registered ourselves */
791 /* CAUTION: *startup becomes invalid with this! */
794 threads_sem_post(psem);
796 #if defined(ENABLE_INTRP)
797 /* set interpreter stack */
800 thread->_global_sp = (Cell *) (intrp_thread_stack + opt_stacksize);
803 // Hook point just before the threads initial method is executed.
804 Hook::thread_start(t);
806 DEBUGTHREADS("starting", t);
808 /* find and run the Thread.run()V method if no other function was passed */
810 if (function == NULL) {
811 #if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
812 /* We need to start the run method of
813 java.lang.VMThread. Since this is a final class, we can use
814 the class object directly. */
816 c = class_java_lang_VMThread;
817 #elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK) || defined(WITH_JAVA_RUNTIME_LIBRARY_CLDC1_1)
818 LLNI_class_get(object, c);
820 # error unknown classpath configuration
823 m = class_resolveclassmethod(c, utf_run, utf_void__void, c, true);
826 vm_abort("threads_startup_thread: run() method not found in class");
828 #if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
830 // We need to start the run method of java.lang.VMThread.
831 java_lang_VMThread jlvmt(jlt.get_vmThread());
832 java_handle_t* h = jlvmt.get_handle();
834 #elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK) || defined(WITH_JAVA_RUNTIME_LIBRARY_CLDC1_1)
836 java_handle_t* h = jlt.get_handle();
839 # error unknown classpath configuration
842 /* Run the thread. */
844 (void) vm_call_method(m, h);
847 /* call passed function, e.g. finalizer_thread */
852 DEBUGTHREADS("stopping", t);
854 // Hook point just after the threads initial method returned.
857 /* We ignore the return value. */
859 (void) thread_detach_current_thread();
865 /* threads_impl_thread_start ***************************************************
867 Start a thread in the JVM. Both (vm internal and java) thread
871 thread....the thread object
872 f.........function to run in the new thread. NULL means that the
873 "run" method of the object `t` should be called
875 ******************************************************************************/
877 void threads_impl_thread_start(threadobject *thread, functionptr f)
885 /* fill startupinfo structure passed by pthread_create to
886 * threads_startup_thread */
888 startup.thread = thread;
889 startup.function = f; /* maybe we don't call Thread.run()V */
891 startup.psem_first = &sem_first;
893 threads_sem_init(&sem, 0, 0);
894 threads_sem_init(&sem_first, 0, 0);
896 /* Initialize thread attributes. */
898 result = pthread_attr_init(&attr);
901 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_init failed");
903 result = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
906 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_setdetachstate failed");
908 /* initialize thread stacksize */
910 result = pthread_attr_setstacksize(&attr, opt_stacksize);
913 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_setstacksize failed");
915 /* create the thread */
917 result = pthread_create(&(thread->tid), &attr, threads_startup_thread, &startup);
920 os::abort_errnum(result, "threads_impl_thread_start: pthread_create failed");
922 /* destroy the thread attributes */
924 result = pthread_attr_destroy(&attr);
927 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_destroy failed");
929 /* signal that pthread_create has returned, so thread->tid is valid */
931 threads_sem_post(&sem_first);
933 /* wait here until the thread has entered itself into the thread list */
935 threads_sem_wait(&sem);
940 sem_destroy(&sem_first);
944 /* threads_set_thread_priority *************************************************
946 Set the priority of the given thread.
949 tid..........thread id
950 priority.....priority to set
952 ******************************************************************************/
954 void threads_set_thread_priority(pthread_t tid, int priority)
956 struct sched_param schedp;
959 pthread_getschedparam(tid, &policy, &schedp);
960 schedp.sched_priority = priority;
961 pthread_setschedparam(tid, policy, &schedp);
966 * Detaches the current thread from the VM.
968 * @return true on success, false otherwise
970 bool thread_detach_current_thread(void)
972 threadobject* t = thread_get_current();
978 /* If the given thread has already been detached, this operation
981 if (thread_is_attached(t) == false)
984 DEBUGTHREADS("detaching", t);
986 java_handle_t* object = thread_get_object(t);
987 java_lang_Thread jlt(object);
989 #if defined(ENABLE_JAVASE)
990 java_handle_t* group = jlt.get_group();
992 /* If there's an uncaught exception, call uncaughtException on the
993 thread's exception handler, or the thread's group if this is
996 java_handle_t* e = exceptions_get_and_clear_exception();
999 /* We use the type void* for handler here, as it's not trivial
1000 to build the java_lang_Thread_UncaughtExceptionHandler
1001 header file with cacaoh. */
1003 # if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
1005 java_handle_t* handler = jlt.get_exceptionHandler();
1007 # elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK)
1009 java_handle_t* handler = jlt.get_uncaughtExceptionHandler();
1016 if (handler != NULL) {
1017 LLNI_class_get(handler, c);
1018 h = (java_handle_t *) handler;
1021 LLNI_class_get(group, c);
1022 h = (java_handle_t *) group;
1025 methodinfo* m = class_resolveclassmethod(c,
1026 utf_uncaughtException,
1027 utf_java_lang_Thread_java_lang_Throwable__V,
1034 (void) vm_call_method(m, h, object, e);
1036 if (exceptions_get_exception())
1040 /* XXX TWISTI: should all threads be in a ThreadGroup? */
1042 /* Remove thread from the thread group. */
1044 if (group != NULL) {
1046 LLNI_class_get(group, c);
1048 # if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
1049 methodinfo* m = class_resolveclassmethod(c,
1051 utf_java_lang_Thread__V,
1052 class_java_lang_ThreadGroup,
1054 # elif defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK)
1055 methodinfo* m = class_resolveclassmethod(c,
1057 utf_java_lang_Thread__V,
1058 class_java_lang_ThreadGroup,
1061 # error unknown classpath configuration
1067 (void) vm_call_method(m, group, object);
1069 if (exceptions_get_exception())
1072 // Clear the ThreadGroup in the Java thread object (Mauve
1073 // test: gnu/testlet/java/lang/Thread/getThreadGroup).
1074 jlt.set_group(NULL);
1078 /* Thread has terminated. */
1080 thread_set_state_terminated(t);
1082 /* Notify all threads waiting on this thread. These are joining
1085 /* XXX Care about exceptions? */
1086 (void) lock_monitor_enter(jlt.get_handle());
1088 lock_notify_all_object(jlt.get_handle());
1090 /* XXX Care about exceptions? */
1091 (void) lock_monitor_exit(jlt.get_handle());
1093 /* Enter the join-mutex before calling thread_free, so
1094 threads_join_all_threads gets the correct number of non-daemon
1097 threads_mutex_join_lock();
1099 /* Free the internal thread data-structure. */
1103 /* Signal that this thread has finished and leave the mutex. */
1105 cond_join->signal();
1106 threads_mutex_join_unlock();
1113 * Internal helper function which suspends the current thread. This is
1114 * the core method of the suspension mechanism actually blocking the
1115 * execution until the suspension reason is cleared again. Note that
1116 * the current thread needs to hold the suspension mutex while calling
1119 static void threads_suspend_self()
1121 threadobject* thread = THREADOBJECT;
1123 DEBUGTHREADS("suspending", thread);
1125 // Mark thread as suspended.
1126 assert(!thread->suspended);
1127 assert(thread->suspend_reason != SUSPEND_REASON_NONE);
1128 thread->suspended = true;
1130 // Acknowledge the suspension.
1131 thread->suspendcond->broadcast();
1133 #if defined(ENABLE_GC_CACAO)
1134 // If we are stopping the world, we should send a global ack.
1135 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD)
1136 threads_sem_post(&suspend_ack);
1139 // Release the suspension mutex and wait till we are resumed.
1140 thread->suspendcond->wait(thread->suspendmutex);
1142 #if defined(ENABLE_GC_CACAO)
1143 // XXX This is propably not ok!
1144 // If we are starting the world, we should send a global ack.
1145 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD)
1146 threads_sem_post(&suspend_ack);
1149 // Mark thread as not suspended.
1150 assert(thread->suspended);
1151 assert(thread->suspend_reason == SUSPEND_REASON_NONE);
1152 thread->suspended = false;
1154 DEBUGTHREADS("resuming", thread);
1159 * Suspend the passed thread. Execution of that thread stops until the thread
1160 * is explicitly resumend again.
1162 * @param thread The thread to be suspended.
1163 * @param reason Reason for suspending the given thread.
1164 * @return True of operation was successful, false otherwise.
1166 bool threads_suspend_thread(threadobject *thread, int32_t reason)
1169 assert(reason != SUSPEND_REASON_NONE);
1171 // Guard this with the suspension mutex.
1172 MutexLocker ml(*thread->suspendmutex);
1174 // Check if thread is already suspended.
1175 if (thread->suspended)
1178 // Check if thread is in the process of suspending.
1179 if (thread->suspend_reason != SUSPEND_REASON_NONE)
1182 // Set the reason for suspending the thread.
1183 thread->suspend_reason = reason;
1185 if (thread == THREADOBJECT) {
1186 // We already hold the suspension mutex and can suspend ourselves
1187 // immediately without using signals at all.
1188 threads_suspend_self();
1191 // Send the suspend signal to the other thread.
1192 if (pthread_kill(thread->tid, SIGUSR1) != 0)
1193 os::abort_errno("threads_suspend_thread: pthread_kill failed");
1195 // Wait for the thread to acknowledge the suspension.
1196 // XXX A possible optimization would be to not wait here, but you
1197 // better think this through twice before trying it!
1198 thread->suspendcond->wait(thread->suspendmutex);
1206 * Resumes execution of the passed thread.
1208 * @param thread The thread to be resumed.
1209 * @param reason Reason for suspending the given thread.
1210 * @return True of operation was successful, false otherwise.
1212 bool threads_resume_thread(threadobject *thread, int32_t reason)
1215 assert(thread != THREADOBJECT);
1216 assert(reason != SUSPEND_REASON_NONE);
1218 // Guard this with the suspension mutex.
1219 MutexLocker ml(*thread->suspendmutex);
1221 // Check if thread really is suspended.
1222 if (!thread->suspended)
1225 // Threads can only be resumed for the same reason they were suspended.
1226 if (thread->suspend_reason != reason)
1229 // Clear the reason for suspending the thread.
1230 thread->suspend_reason = SUSPEND_REASON_NONE;
1232 // Tell everyone that the thread should resume.
1233 thread->suspendcond->broadcast();
1240 * Acknowledges the suspension of the current thread.
1242 void threads_suspend_ack()
1244 threadobject* thread = THREADOBJECT;
1246 // Guard this with the suspension mutex.
1247 MutexLocker ml(*thread->suspendmutex);
1249 // Suspend ourselves while holding the suspension mutex.
1250 threads_suspend_self();
1254 /* threads_join_all_threads ****************************************************
1256 Join all non-daemon threads.
1258 *******************************************************************************/
1260 void threads_join_all_threads(void)
1264 /* get current thread */
1268 /* This thread is waiting for all non-daemon threads to exit. */
1270 thread_set_state_waiting(t);
1272 /* enter join mutex */
1274 threads_mutex_join_lock();
1276 /* Wait for condition as long as we have non-daemon threads. We
1277 compare against 1 because the current (main thread) is also a
1278 non-daemon thread. */
1280 while (ThreadList::get_number_of_non_daemon_threads() > 1)
1281 cond_join->wait(mutex_join);
1283 /* leave join mutex */
1285 threads_mutex_join_unlock();
1289 /* threads_timespec_earlier ****************************************************
1291 Return true if timespec tv1 is earlier than timespec tv2.
1294 tv1..........first timespec
1295 tv2..........second timespec
1298 true, if the first timespec is earlier
1300 *******************************************************************************/
1302 static inline bool threads_timespec_earlier(const struct timespec *tv1,
1303 const struct timespec *tv2)
1305 return (tv1->tv_sec < tv2->tv_sec)
1307 (tv1->tv_sec == tv2->tv_sec && tv1->tv_nsec < tv2->tv_nsec);
1311 /* threads_current_time_is_earlier_than ****************************************
1313 Check if the current time is earlier than the given timespec.
1316 tv...........the timespec to compare against
1319 true, if the current time is earlier
1321 *******************************************************************************/
1323 static bool threads_current_time_is_earlier_than(const struct timespec *tv)
1325 struct timeval tvnow;
1326 struct timespec tsnow;
1328 /* get current time */
1330 if (gettimeofday(&tvnow, NULL) != 0)
1331 vm_abort("gettimeofday failed: %s\n", strerror(errno));
1333 /* convert it to a timespec */
1335 tsnow.tv_sec = tvnow.tv_sec;
1336 tsnow.tv_nsec = tvnow.tv_usec * 1000;
1338 /* compare current time with the given timespec */
1340 return threads_timespec_earlier(&tsnow, tv);
1344 /* threads_wait_with_timeout ***************************************************
1346 Wait until the given point in time on a monitor until either
1347 we are notified, we are interrupted, or the time is up.
1350 t............the current thread
1351 wakeupTime...absolute (latest) wakeup time
1352 If both tv_sec and tv_nsec are zero, this function
1353 waits for an unlimited amount of time.
1355 *******************************************************************************/
1357 static void threads_wait_with_timeout(threadobject *t, struct timespec *wakeupTime, bool parking)
1359 // Acquire the waitmutex.
1360 t->waitmutex->lock();
1362 /* wait on waitcond */
1364 if (wakeupTime->tv_sec || wakeupTime->tv_nsec) {
1366 while (!t->interrupted && !(parking ? t->park_permit : t->signaled)
1367 && threads_current_time_is_earlier_than(wakeupTime))
1370 thread_set_state_timed_parked(t);
1372 thread_set_state_timed_waiting(t);
1374 t->waitcond->timedwait(t->waitmutex, wakeupTime);
1376 thread_set_state_runnable(t);
1381 while (!t->interrupted && !(parking ? t->park_permit : t->signaled)) {
1383 thread_set_state_parked(t);
1385 thread_set_state_waiting(t);
1387 t->waitcond->wait(t->waitmutex);
1389 thread_set_state_runnable(t);
1394 t->park_permit = false;
1396 // Release the waitmutex.
1397 t->waitmutex->unlock();
1401 /* threads_wait_with_timeout_relative ******************************************
1403 Wait for the given maximum amount of time on a monitor until either
1404 we are notified, we are interrupted, or the time is up.
1407 t............the current thread
1408 millis.......milliseconds to wait
1409 nanos........nanoseconds to wait
1411 *******************************************************************************/
1413 void threads_wait_with_timeout_relative(threadobject *thread, s8 millis,
1416 struct timespec wakeupTime;
1418 /* calculate the the (latest) wakeup time */
1420 threads_calc_absolute_time(&wakeupTime, millis, nanos);
1424 threads_wait_with_timeout(thread, &wakeupTime, false);
1428 /* threads_calc_absolute_time **************************************************
1430 Calculate the absolute point in time a given number of ms and ns from now.
1433 millis............milliseconds from now
1434 nanos.............nanoseconds from now
1437 *tm...............receives the timespec of the absolute point in time
1439 *******************************************************************************/
1441 static void threads_calc_absolute_time(struct timespec *tm, s8 millis, s4 nanos)
1443 // (at least with GNU classpath) we know that 0 <= nanos <= 999999
1445 if (!millis && !nanos)
1448 gettimeofday(&tv, NULL);
1449 s8 secs = tv.tv_sec + millis / 1000;
1450 if (secs > INT32_MAX) // integer overflow
1454 long nsec = tv.tv_usec * 1000 + (s4) millis * 1000000 + nanos;
1455 tm->tv_sec = tv.tv_sec + nsec / 1000000000;
1456 if (tm->tv_sec < tv.tv_sec) // integer overflow
1458 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, false);
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 * Park the current thread for the specified amount of time or until a
1558 * specified deadline.
1560 * @param absolute Is the time in nanos a deadline or a duration?
1561 * @param nanos Nanoseconds to park (absolute=false)
1562 * or deadline in milliseconds (absolute=true)
1564 void threads_park(bool absolute, int64_t nanos)
1567 struct timespec wakeupTime;
1569 t = thread_get_current();
1572 wakeupTime.tv_nsec = 0;
1573 wakeupTime.tv_sec = nanos / 1000; /* milliseconds */
1576 threads_calc_absolute_time(&wakeupTime, nanos / 1000000, nanos % 1000000);
1578 threads_wait_with_timeout(t, &wakeupTime, true);
1582 * Unpark the specified thread.
1584 * @param t The thread to unpark.
1586 void threads_unpark(threadobject *t)
1588 t->waitmutex->lock();
1590 t->waitcond->signal();
1592 t->park_permit = true;
1594 t->waitmutex->unlock();
1598 /* threads_yield ***************************************************************
1600 Yield to the scheduler.
1602 *******************************************************************************/
1604 void threads_yield(void)
1609 #if defined(ENABLE_TLH)
1611 void threads_tlh_add_frame() {
1612 tlh_add_frame(&(THREADOBJECT->tlh));
1615 void threads_tlh_remove_frame() {
1616 tlh_remove_frame(&(THREADOBJECT->tlh));
1623 * These are local overrides for various environment variables in Emacs.
1624 * Please do not remove this and leave it at the end of the file, where
1625 * Emacs will automagically detect them.
1626 * ---------------------------------------------------------------------
1629 * indent-tabs-mode: t
1633 * vim:noexpandtab:sw=4:ts=4: