1 /* src/threads/posix/thread-posix.cpp - POSIX thread functions
3 Copyright (C) 1996-2011
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
101 #elif defined(__SOLARIS__)
102 # define GC_SOLARIS_THREADS
105 #if defined(ENABLE_GC_BOEHM)
106 /* We need to include Boehm's gc.h here because it overrides
107 pthread_create and friends. */
108 # include "mm/boehm-gc/include/gc.h"
112 #if defined(__DARWIN__)
113 /* Darwin has no working semaphore implementation. This one is taken
117 This is a very simple semaphore implementation for Darwin. It
118 is implemented in terms of pthreads calls so it isn't async signal
119 safe. This isn't a problem because signals aren't used to
120 suspend threads on Darwin.
123 static int sem_init(sem_t *sem, int pshared, int value)
128 sem->mutex = new Mutex();
129 sem->cond = new Condition();
135 static int sem_post(sem_t *sem)
140 sem->mutex->unlock();
145 static int sem_wait(sem_t *sem)
149 while (sem->value == 0) {
150 sem->cond->wait(sem->mutex);
154 sem->mutex->unlock();
159 static int sem_destroy(sem_t *sem)
166 #endif /* defined(__DARWIN__) */
169 /* startupinfo *****************************************************************
171 Struct used to pass info from threads_start_thread to
172 threads_startup_thread.
174 ******************************************************************************/
177 threadobject *thread; /* threadobject for this thread */
178 functionptr function; /* function to run in the new thread */
179 sem_t *psem; /* signals when thread has been entered */
180 /* in the thread list */
181 sem_t *psem_first; /* signals when pthread_create has returned */
185 /* prototypes *****************************************************************/
187 static void threads_calc_absolute_time(struct timespec *tm, s8 millis, s4 nanos);
190 /******************************************************************************/
191 /* GLOBAL VARIABLES */
192 /******************************************************************************/
194 /* the thread object of the current thread */
195 /* This is either a thread-local variable defined with __thread, or */
196 /* a thread-specific value stored with key threads_current_threadobject_key. */
197 #if defined(HAVE___THREAD)
198 __thread threadobject *thread_current;
200 pthread_key_t thread_current_key;
203 /* global mutex for stop-the-world */
204 static Mutex* stopworldlock;
206 #if defined(ENABLE_GC_CACAO)
207 /* global mutex for the GC */
208 static Mutex* mutex_gc;
211 /* global mutex and condition for joining threads on exit */
212 static Condition* cond_join;
214 #if defined(ENABLE_GC_CACAO)
215 /* semaphore used for acknowleding thread suspension */
216 static sem_t suspend_ack;
220 /* threads_sem_init ************************************************************
222 Initialize a semaphore. Checks against errors and interruptions.
225 sem..............the semaphore to initialize
226 shared...........true if this semaphore will be shared between processes
227 value............the initial value for the semaphore
229 *******************************************************************************/
231 void threads_sem_init(sem_t *sem, bool shared, int value)
238 r = sem_init(sem, shared, value);
241 } while (errno == EINTR);
243 vm_abort("sem_init failed: %s", strerror(errno));
247 /* threads_sem_wait ************************************************************
249 Wait for a semaphore, non-interruptible.
251 IMPORTANT: Always use this function instead of `sem_wait` directly, as
252 `sem_wait` may be interrupted by signals!
255 sem..............the semaphore to wait on
257 *******************************************************************************/
259 void threads_sem_wait(sem_t *sem)
269 } while (errno == EINTR);
271 vm_abort("sem_wait failed: %s", strerror(errno));
275 /* threads_sem_post ************************************************************
277 Increase the count of a semaphore. Checks for errors.
280 sem..............the semaphore to increase the count of
282 *******************************************************************************/
284 void threads_sem_post(sem_t *sem)
290 /* unlike sem_wait, sem_post is not interruptible */
296 vm_abort("sem_post failed: %s", strerror(errno));
300 /* threads_stopworld ***********************************************************
302 Stops the world from turning. All threads except the calling one
303 are suspended. The function returns as soon as all threads have
304 acknowledged their suspension.
306 *******************************************************************************/
308 #if defined(ENABLE_GC_CACAO)
309 void threads_stopworld(void)
311 #if !defined(__DARWIN__) && !defined(__CYGWIN__)
318 stopworldlock->lock();
320 /* lock the threads lists */
324 #if defined(__DARWIN__)
325 /*threads_cast_darwinstop();*/
327 #elif defined(__CYGWIN__)
333 DEBUGTHREADS("stops World", self);
337 /* suspend all running threads */
338 for (t = threadlist_first(); t != NULL; t = threadlist_next(t)) {
339 /* don't send the signal to ourself */
344 /* don't send the signal to NEW threads (because they are not
345 completely initialized) */
347 if (t->state == THREAD_STATE_NEW)
350 /* send the signal */
352 result = threads_suspend_thread(t, SUSPEND_REASON_STOPWORLD);
355 /* increase threads count */
360 /* wait for all threads signaled to suspend */
361 for (i = 0; i < count; i++)
362 threads_sem_wait(&suspend_ack);
365 /* ATTENTION: Don't unlock the threads-lists here so that
366 non-signaled NEW threads can't change their state and execute
372 /* threads_startworld **********************************************************
374 Starts the world again after it has previously been stopped.
376 *******************************************************************************/
378 #if defined(ENABLE_GC_CACAO)
379 void threads_startworld(void)
381 #if !defined(__DARWIN__) && !defined(__CYGWIN__)
388 #if defined(__DARWIN__)
389 /*threads_cast_darwinresume();*/
391 #elif defined(__IRIX__)
392 threads_cast_irixresume();
393 #elif defined(__CYGWIN__)
399 DEBUGTHREADS("starts World", self);
403 /* resume all thread we haltet */
404 for (t = threadlist_first(); t != NULL; t = threadlist_next(t)) {
405 /* don't send the signal to ourself */
410 /* don't send the signal to NEW threads (because they are not
411 completely initialized) */
413 if (t->state == THREAD_STATE_NEW)
416 /* send the signal */
418 result = threads_resume_thread(t);
421 /* increase threads count */
426 /* wait for all threads signaled to suspend */
427 for (i = 0; i < count; i++)
428 threads_sem_wait(&suspend_ack);
432 /* unlock the threads lists */
436 stopworldlock->unlock();
441 /* threads_impl_thread_clear ***************************************************
443 Clears all fields in threadobject the way an MZERO would have
444 done. MZERO cannot be used anymore because it would mess up the
448 t....the threadobject
450 *******************************************************************************/
452 void threads_impl_thread_clear(threadobject *t)
461 t->is_in_active_list = false;
465 #if defined(__DARWIN__)
469 t->interrupted = false;
472 t->suspended = false;
473 t->suspend_reason = 0;
477 t->_exceptionptr = NULL;
478 t->_stackframeinfo = NULL;
479 t->_localref_table = NULL;
481 #if defined(ENABLE_INTRP)
482 t->_global_sp = NULL;
485 #if defined(ENABLE_GC_CACAO)
486 t->gc_critical = false;
492 // Simply reuse the existing dump memory.
495 /* threads_impl_thread_reuse ***************************************************
497 Resets some implementation fields in threadobject. This was
498 previously done in threads_impl_thread_new.
501 t....the threadobject
503 *******************************************************************************/
505 void threads_impl_thread_reuse(threadobject *t)
507 /* get the pthread id */
509 t->tid = pthread_self();
511 #if defined(ENABLE_DEBUG_FILTER)
512 /* Initialize filter counters */
513 t->filterverbosecallctr[0] = 0;
514 t->filterverbosecallctr[1] = 0;
518 t->tracejavacallindent = 0;
519 t->tracejavacallcount = 0;
526 /* not really needed */
527 t->flc_object = NULL;
529 #if defined(ENABLE_TLH)
530 tlh_destroy(&(t->tlh));
535 void threads_impl_clear_heap_pointers(threadobject *t)
541 /* threads_impl_preinit ********************************************************
543 Do some early initialization of stuff required.
545 ATTENTION: Do NOT use any Java heap allocation here, as gc_init()
546 is called AFTER this function!
548 *******************************************************************************/
550 void threads_impl_preinit(void)
552 stopworldlock = new Mutex();
554 /* initialize exit mutex and condition (on exit we join all
557 cond_join = new Condition();
559 #if defined(ENABLE_GC_CACAO)
560 /* initialize the GC mutex & suspend semaphore */
562 mutex_gc = new Mutex();
563 threads_sem_init(&suspend_ack, 0, 0);
566 #if !defined(HAVE___THREAD)
567 int result = pthread_key_create(&thread_current_key, NULL);
569 os::abort_errnum(result, "threads_impl_preinit: pthread_key_create failed");
574 /* threads_mutex_gc_lock *******************************************************
576 Enter the global GC mutex.
578 *******************************************************************************/
580 #if defined(ENABLE_GC_CACAO)
581 void threads_mutex_gc_lock(void)
588 /* threads_mutex_gc_unlock *****************************************************
590 Leave the global GC mutex.
592 *******************************************************************************/
594 #if defined(ENABLE_GC_CACAO)
595 void threads_mutex_gc_unlock(void)
601 /* threads_impl_init ***********************************************************
603 Initializes the implementation specific bits.
605 *******************************************************************************/
607 void threads_impl_init(void)
612 threads_set_thread_priority(pthread_self(), NORM_PRIORITY);
614 /* Initialize the thread attribute object. */
616 result = pthread_attr_init(&attr);
619 os::abort_errnum(result, "threads_impl_init: pthread_attr_init failed");
621 result = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
624 os::abort_errnum(result, "threads_impl_init: pthread_attr_setdetachstate failed");
628 /* threads_startup_thread ******************************************************
630 Thread startup function called by pthread_create.
632 Thread which have a startup.function != NULL are marked as internal
633 threads. All other threads are threated as normal Java threads.
635 NOTE: This function is not called directly by pthread_create. The Boehm GC
636 inserts its own GC_start_routine in between, which then calls
640 arg..........the argument passed to pthread_create, ie. a pointer to
641 a startupinfo struct. CAUTION: When the `psem` semaphore
642 is posted, the startupinfo struct becomes invalid! (It
643 is allocated on the stack of threads_start_thread.)
645 ******************************************************************************/
647 static void *threads_startup_thread(void *arg)
649 startupinfo *startup;
654 functionptr function;
656 #if defined(ENABLE_GC_BOEHM)
657 # if !defined(__DARWIN__)
658 struct GC_stack_base sb;
663 #if defined(ENABLE_INTRP)
664 u1 *intrp_thread_stack;
667 #if defined(ENABLE_INTRP)
668 /* create interpreter stack */
671 intrp_thread_stack = GCMNEW(u1, opt_stacksize);
672 MSET(intrp_thread_stack, 0, u1, opt_stacksize);
675 intrp_thread_stack = NULL;
678 /* get passed startupinfo structure and the values in there */
680 startup = (startupinfo*) arg;
683 function = startup->function;
684 psem = startup->psem;
686 /* Seems like we've encountered a situation where thread->tid was
687 not set by pthread_create. We alleviate this problem by waiting
688 for pthread_create to return. */
690 threads_sem_wait(startup->psem_first);
692 #if defined(__DARWIN__)
693 t->mach_thread = mach_thread_self();
696 /* Now that we are in the new thread, we can store the internal
697 thread data-structure in the TSD. */
699 thread_set_current(t);
701 #if defined(ENABLE_GC_BOEHM)
702 # if defined(__DARWIN__)
703 // This is currently not implemented in Boehm-GC. Just fail silently.
705 /* Register the thread with Boehm-GC. This must happen before the
706 thread allocates any memory from the GC heap.*/
708 result = GC_get_stack_base(&sb);
711 vm_abort("threads_startup_thread: GC_get_stack_base failed: result=%d", result);
713 GC_register_my_thread(&sb);
717 // Get the java.lang.Thread object for this thread.
718 java_handle_t* object = LLNI_WRAP(t->object);
719 java_lang_Thread jlt(object);
721 /* set our priority */
723 threads_set_thread_priority(t->tid, jlt.get_priority());
725 /* tell threads_startup_thread that we registered ourselves */
726 /* CAUTION: *startup becomes invalid with this! */
729 threads_sem_post(psem);
731 #if defined(ENABLE_INTRP)
732 /* set interpreter stack */
735 thread->_global_sp = (Cell *) (intrp_thread_stack + opt_stacksize);
738 // Hook point just before the threads initial method is executed.
739 Hook::thread_start(t);
741 DEBUGTHREADS("starting", t);
743 /* find and run the Thread.run()V method if no other function was passed */
745 if (function == NULL) {
746 c = ThreadRuntime::get_thread_class_from_object(object);
748 m = class_resolveclassmethod(c, utf_run, utf_void__void, c, true);
751 vm_abort("threads_startup_thread: run() method not found in class");
753 java_handle_t *h = ThreadRuntime::get_vmthread_handle(jlt);
755 /* Run the thread. */
757 (void) vm_call_method(m, h);
760 /* call passed function, e.g. finalizer_thread */
765 DEBUGTHREADS("stopping", t);
767 // Hook point just after the threads initial method returned.
770 /* We ignore the return value. */
772 (void) thread_detach_current_thread();
778 /* threads_impl_thread_start ***************************************************
780 Start a thread in the JVM. Both (vm internal and java) thread
784 thread....the thread object
785 f.........function to run in the new thread. NULL means that the
786 "run" method of the object `t` should be called
788 ******************************************************************************/
790 void threads_impl_thread_start(threadobject *thread, functionptr f)
798 /* fill startupinfo structure passed by pthread_create to
799 * threads_startup_thread */
801 startup.thread = thread;
802 startup.function = f; /* maybe we don't call Thread.run()V */
804 startup.psem_first = &sem_first;
806 threads_sem_init(&sem, 0, 0);
807 threads_sem_init(&sem_first, 0, 0);
809 /* Initialize thread attributes. */
811 result = pthread_attr_init(&attr);
814 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_init failed");
816 result = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
819 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_setdetachstate failed");
821 /* initialize thread stacksize */
823 result = pthread_attr_setstacksize(&attr, opt_stacksize);
826 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_setstacksize failed");
828 /* create the thread */
830 result = pthread_create(&(thread->tid), &attr, threads_startup_thread, &startup);
833 os::abort_errnum(result, "threads_impl_thread_start: pthread_create failed");
835 /* destroy the thread attributes */
837 result = pthread_attr_destroy(&attr);
840 os::abort_errnum(result, "threads_impl_thread_start: pthread_attr_destroy failed");
842 /* signal that pthread_create has returned, so thread->tid is valid */
844 threads_sem_post(&sem_first);
846 /* wait here until the thread has entered itself into the thread list */
848 threads_sem_wait(&sem);
853 sem_destroy(&sem_first);
857 /* threads_set_thread_priority *************************************************
859 Set the priority of the given thread.
862 tid..........thread id
863 priority.....priority to set
865 ******************************************************************************/
867 void threads_set_thread_priority(pthread_t tid, int priority)
869 struct sched_param schedp;
872 pthread_getschedparam(tid, &policy, &schedp);
873 schedp.sched_priority = priority;
874 pthread_setschedparam(tid, policy, &schedp);
879 * Detaches the current thread from the VM.
881 * @return true on success, false otherwise
883 bool thread_detach_current_thread(void)
885 threadobject* t = thread_get_current();
891 /* If the given thread has already been detached, this operation
894 if (thread_is_attached(t) == false)
897 DEBUGTHREADS("detaching", t);
899 java_handle_t* object = LLNI_WRAP(t->object);
900 java_lang_Thread jlt(object);
902 #if defined(ENABLE_JAVASE)
903 java_handle_t* group = jlt.get_group();
905 /* If there's an uncaught exception, call uncaughtException on the
906 thread's exception handler, or the thread's group if this is
909 java_handle_t* e = exceptions_get_and_clear_exception();
912 /* We use the type void* for handler here, as it's not trivial
913 to build the java_lang_Thread_UncaughtExceptionHandler
914 header file with cacaoh. */
916 java_handle_t *handler = ThreadRuntime::get_thread_exception_handler(jlt);
921 if (handler != NULL) {
922 LLNI_class_get(handler, c);
923 h = (java_handle_t *) handler;
926 LLNI_class_get(group, c);
927 h = (java_handle_t *) group;
930 methodinfo* m = class_resolveclassmethod(c,
931 utf_uncaughtException,
932 utf_java_lang_Thread_java_lang_Throwable__V,
939 (void) vm_call_method(m, h, object, e);
941 if (exceptions_get_exception())
945 /* XXX TWISTI: should all threads be in a ThreadGroup? */
947 /* Remove thread from the thread group. */
951 LLNI_class_get(group, c);
953 methodinfo *m = ThreadRuntime::get_threadgroup_remove_method(c);
958 (void) vm_call_method(m, group, object);
960 if (exceptions_get_exception())
963 // Clear the ThreadGroup in the Java thread object (Mauve
964 // test: gnu/testlet/java/lang/Thread/getThreadGroup).
969 /* Thread has terminated. */
971 thread_set_state_terminated(t);
973 /* Notify all threads waiting on this thread. These are joining
976 /* XXX Care about exceptions? */
977 (void) lock_monitor_enter(jlt.get_handle());
979 lock_notify_all_object(jlt.get_handle());
981 /* XXX Care about exceptions? */
982 (void) lock_monitor_exit(jlt.get_handle());
984 t->waitmutex->lock();
986 t->waitmutex->unlock();
990 /* Free the internal thread data-structure. */
994 /* Signal that this thread has finished and leave the mutex. */
997 ThreadList::unlock();
999 t->suspendmutex->lock();
1000 t->suspendmutex->unlock();
1007 * Internal helper function which suspends the current thread. This is
1008 * the core method of the suspension mechanism actually blocking the
1009 * execution until the suspension reason is cleared again. Note that
1010 * the current thread needs to hold the suspension mutex while calling
1013 static void threads_suspend_self()
1015 threadobject* thread = THREADOBJECT;
1017 DEBUGTHREADS("suspending", thread);
1019 // Mark thread as suspended.
1020 assert(!thread->suspended);
1021 assert(thread->suspend_reason != SUSPEND_REASON_NONE);
1022 thread->suspended = true;
1024 // Acknowledge the suspension.
1025 thread->suspendcond->broadcast();
1027 #if defined(ENABLE_GC_CACAO)
1028 // If we are stopping the world, we should send a global ack.
1029 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD)
1030 threads_sem_post(&suspend_ack);
1033 // Release the suspension mutex and wait till we are resumed.
1034 while (thread->suspend_reason != SUSPEND_REASON_NONE)
1035 thread->suspendcond->wait(thread->suspendmutex);
1037 #if defined(ENABLE_GC_CACAO)
1038 // XXX This is propably not ok!
1039 // If we are starting the world, we should send a global ack.
1040 if (thread->suspend_reason == SUSPEND_REASON_STOPWORLD)
1041 threads_sem_post(&suspend_ack);
1044 // Mark thread as not suspended.
1045 assert(thread->suspended);
1046 assert(thread->suspend_reason == SUSPEND_REASON_NONE);
1047 thread->suspended = false;
1049 DEBUGTHREADS("resuming", thread);
1054 * Suspend the passed thread. Execution of that thread stops until the thread
1055 * is explicitly resumed again.
1057 * @param thread The thread to be suspended.
1058 * @param reason Reason for suspending the given thread.
1059 * @return True of operation was successful, false otherwise.
1061 bool threads_suspend_thread(threadobject *thread, int32_t reason)
1064 assert(reason != SUSPEND_REASON_NONE);
1066 // Guard this with the suspension mutex.
1067 MutexLocker ml(*thread->suspendmutex);
1069 // Check if thread is already suspended.
1070 if (thread->suspended)
1073 // Check if thread is in the process of suspending.
1074 if (thread->suspend_reason != SUSPEND_REASON_NONE)
1077 // Set the reason for suspending the thread.
1078 thread->suspend_reason = reason;
1080 if (thread == THREADOBJECT) {
1081 // We already hold the suspension mutex and can suspend ourselves
1082 // immediately without using signals at all.
1083 threads_suspend_self();
1086 // Send the suspend signal to the other thread.
1089 if (pthread_kill(thread->tid, SIGUSR1) != 0)
1090 os::abort_errno("threads_suspend_thread: pthread_kill failed");
1092 // Wait for the thread to acknowledge the suspension.
1093 while (!thread->suspended)
1094 thread->suspendcond->wait(thread->suspendmutex);
1102 * Resumes execution of the passed thread.
1104 * @param thread The thread to be resumed.
1105 * @param reason Reason for suspending the given thread.
1106 * @return True of operation was successful, false otherwise.
1108 bool threads_resume_thread(threadobject *thread, int32_t reason)
1111 assert(thread != THREADOBJECT);
1112 assert(reason != SUSPEND_REASON_NONE);
1114 // Guard this with the suspension mutex.
1115 MutexLocker ml(*thread->suspendmutex);
1117 // Check if thread really is suspended.
1118 if (!thread->suspended)
1121 // Threads can only be resumed for the same reason they were suspended.
1122 if (thread->suspend_reason != reason)
1125 // Clear the reason for suspending the thread.
1126 thread->suspend_reason = SUSPEND_REASON_NONE;
1128 // Tell everyone that the thread should resume.
1129 thread->suspendcond->broadcast();
1136 * Acknowledges the suspension of the current thread.
1138 void threads_suspend_ack()
1140 threadobject* thread = THREADOBJECT;
1142 // Guard this with the suspension mutex.
1143 MutexLocker ml(*thread->suspendmutex);
1145 // Suspend ourselves while holding the suspension mutex.
1146 threads_suspend_self();
1150 /* threads_join_all_threads ****************************************************
1152 Join all non-daemon threads.
1154 *******************************************************************************/
1156 void threads_join_all_threads(void)
1160 /* get current thread */
1164 /* This thread is waiting for all non-daemon threads to exit. */
1166 thread_set_state_waiting(t);
1168 /* enter join mutex */
1172 /* Wait for condition as long as we have non-daemon threads. We
1173 compare against 1 because the current (main thread) is also a
1174 non-daemon thread. */
1176 while (ThreadList::get_number_of_non_daemon_threads() > 1)
1177 ThreadList::wait_cond(cond_join);
1179 /* leave join mutex */
1181 ThreadList::unlock();
1185 /* threads_timespec_earlier ****************************************************
1187 Return true if timespec tv1 is earlier than timespec tv2.
1190 tv1..........first timespec
1191 tv2..........second timespec
1194 true, if the first timespec is earlier
1196 *******************************************************************************/
1198 static inline bool threads_timespec_earlier(const struct timespec *tv1,
1199 const struct timespec *tv2)
1201 return (tv1->tv_sec < tv2->tv_sec)
1203 (tv1->tv_sec == tv2->tv_sec && tv1->tv_nsec < tv2->tv_nsec);
1207 /* threads_current_time_is_earlier_than ****************************************
1209 Check if the current time is earlier than the given timespec.
1212 tv...........the timespec to compare against
1215 true, if the current time is earlier
1217 *******************************************************************************/
1219 static bool threads_current_time_is_earlier_than(const struct timespec *tv)
1221 struct timeval tvnow;
1222 struct timespec tsnow;
1224 /* get current time */
1226 if (gettimeofday(&tvnow, NULL) != 0)
1227 vm_abort("gettimeofday failed: %s\n", strerror(errno));
1229 /* convert it to a timespec */
1231 tsnow.tv_sec = tvnow.tv_sec;
1232 tsnow.tv_nsec = tvnow.tv_usec * 1000;
1234 /* compare current time with the given timespec */
1236 return threads_timespec_earlier(&tsnow, tv);
1240 /* threads_wait_with_timeout ***************************************************
1242 Wait until the given point in time on a monitor until either
1243 we are notified, we are interrupted, or the time is up.
1246 t............the current thread
1247 wakeupTime...absolute (latest) wakeup time
1248 If both tv_sec and tv_nsec are zero, this function
1249 waits for an unlimited amount of time.
1251 *******************************************************************************/
1253 static void threads_wait_with_timeout(threadobject *t, struct timespec *wakeupTime, bool parking)
1255 // Acquire the waitmutex.
1256 t->waitmutex->lock();
1258 /* wait on waitcond */
1260 if (wakeupTime->tv_sec || wakeupTime->tv_nsec) {
1262 while (!t->interrupted && !(parking ? t->park_permit : t->signaled)
1263 && threads_current_time_is_earlier_than(wakeupTime))
1266 thread_set_state_timed_parked(t);
1268 thread_set_state_timed_waiting(t);
1270 t->waitcond->timedwait(t->waitmutex, wakeupTime);
1272 thread_set_state_runnable(t);
1277 while (!t->interrupted && !(parking ? t->park_permit : t->signaled)) {
1279 thread_set_state_parked(t);
1281 thread_set_state_waiting(t);
1283 t->waitcond->wait(t->waitmutex);
1285 thread_set_state_runnable(t);
1290 t->park_permit = false;
1292 // Release the waitmutex.
1293 t->waitmutex->unlock();
1297 /* threads_wait_with_timeout_relative ******************************************
1299 Wait for the given maximum amount of time on a monitor until either
1300 we are notified, we are interrupted, or the time is up.
1303 t............the current thread
1304 millis.......milliseconds to wait
1305 nanos........nanoseconds to wait
1307 *******************************************************************************/
1309 void threads_wait_with_timeout_relative(threadobject *thread, s8 millis,
1312 struct timespec wakeupTime;
1314 /* calculate the the (latest) wakeup time */
1316 threads_calc_absolute_time(&wakeupTime, millis, nanos);
1320 threads_wait_with_timeout(thread, &wakeupTime, false);
1324 /* threads_calc_absolute_time **************************************************
1326 Calculate the absolute point in time a given number of ms and ns from now.
1329 millis............milliseconds from now
1330 nanos.............nanoseconds from now
1333 *tm...............receives the timespec of the absolute point in time
1335 *******************************************************************************/
1337 static void threads_calc_absolute_time(struct timespec *tm, s8 millis, s4 nanos)
1339 // (at least with GNU classpath) we know that 0 <= nanos <= 999999
1341 if (!millis && !nanos)
1344 gettimeofday(&tv, NULL);
1345 s8 secs = tv.tv_sec + millis / 1000;
1346 if (secs > INT32_MAX) // integer overflow
1350 long nsec = tv.tv_usec * 1000 + (s4) millis * 1000000 + nanos;
1351 tm->tv_sec = tv.tv_sec + nsec / 1000000000;
1352 if (tm->tv_sec < tv.tv_sec) // integer overflow
1354 tm->tv_nsec = nsec % 1000000000;
1362 /* threads_thread_interrupt ****************************************************
1364 Interrupt the given thread.
1366 The thread gets the "waitcond" signal and
1367 its interrupted flag is set to true.
1370 thread............the thread to interrupt
1372 *******************************************************************************/
1374 void threads_thread_interrupt(threadobject *t)
1376 /* Signal the thread a "waitcond" and tell it that it has been
1379 t->waitmutex->lock();
1381 DEBUGTHREADS("interrupted", t);
1383 /* Interrupt blocking system call using a signal. */
1386 pthread_kill(t->tid, Signal_INTERRUPT_SYSTEM_CALL);
1388 t->waitcond->signal();
1390 t->interrupted = true;
1392 t->waitmutex->unlock();
1397 * Sleep the current thread for the specified amount of time.
1399 * @param millis Milliseconds to sleep.
1400 * @param nanos Nanoseconds to sleep.
1402 void threads_sleep(int64_t millis, int32_t nanos)
1405 struct timespec wakeupTime;
1409 /* exceptions_throw_illegalargumentexception("timeout value is negative"); */
1410 exceptions_throw_illegalargumentexception();
1414 t = thread_get_current();
1416 if (thread_is_interrupted(t) && !exceptions_get_exception()) {
1417 /* Clear interrupted flag (Mauve test:
1418 gnu/testlet/java/lang/Thread/interrupt). */
1420 thread_set_interrupted(t, false);
1422 /* exceptions_throw_interruptedexception("sleep interrupted"); */
1423 exceptions_throw_interruptedexception();
1427 // (Note taken from classpath/vm/reference/java/lang/VMThread.java (sleep))
1428 // Note: JDK treats a zero length sleep is like Thread.yield(),
1429 // without checking the interrupted status of the thread. It's
1430 // unclear if this is a bug in the implementation or the spec.
1431 // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6213203 */
1432 if (millis == 0 && nanos == 0) {
1436 threads_calc_absolute_time(&wakeupTime, millis, nanos);
1438 threads_wait_with_timeout(t, &wakeupTime, false);
1440 interrupted = thread_is_interrupted(t);
1443 thread_set_interrupted(t, false);
1445 // An other exception could have been thrown
1446 // (e.g. ThreadDeathException).
1447 if (!exceptions_get_exception())
1448 exceptions_throw_interruptedexception();
1454 * Park the current thread for the specified amount of time or until a
1455 * specified deadline.
1457 * @param absolute Is the time in nanos a deadline or a duration?
1458 * @param nanos Nanoseconds to park (absolute=false)
1459 * or deadline in milliseconds (absolute=true)
1461 void threads_park(bool absolute, int64_t nanos)
1464 struct timespec wakeupTime;
1466 t = thread_get_current();
1469 wakeupTime.tv_nsec = 0;
1470 wakeupTime.tv_sec = nanos / 1000; /* milliseconds */
1473 threads_calc_absolute_time(&wakeupTime, nanos / 1000000, nanos % 1000000);
1475 threads_wait_with_timeout(t, &wakeupTime, true);
1479 * Unpark the specified thread.
1481 * @param t The thread to unpark.
1483 void threads_unpark(threadobject *t)
1485 t->waitmutex->lock();
1487 t->waitcond->signal();
1489 t->park_permit = true;
1491 t->waitmutex->unlock();
1495 /* threads_yield ***************************************************************
1497 Yield to the scheduler.
1499 *******************************************************************************/
1501 void threads_yield(void)
1506 #if defined(ENABLE_TLH)
1508 void threads_tlh_add_frame() {
1509 tlh_add_frame(&(THREADOBJECT->tlh));
1512 void threads_tlh_remove_frame() {
1513 tlh_remove_frame(&(THREADOBJECT->tlh));
1520 * These are local overrides for various environment variables in Emacs.
1521 * Please do not remove this and leave it at the end of the file, where
1522 * Emacs will automagically detect them.
1523 * ---------------------------------------------------------------------
1526 * indent-tabs-mode: t
1530 * vim:noexpandtab:sw=4:ts=4: