1 // posix-threads.cc - interface between libjava and POSIX threads.
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2004 Free Software Foundation
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
12 // * Document signal handling limitations
16 // If we're using the Boehm GC, then we need to override some of the
17 // thread primitives. This is fairly gross.
20 #endif /* HAVE_BOEHM_GC */
28 #include <unistd.h> // To test for _POSIX_THREAD_PRIORITY_SCHEDULING
33 #include <java/lang/Thread.h>
34 #include <java/lang/System.h>
35 #include <java/lang/Long.h>
36 #include <java/lang/OutOfMemoryError.h>
37 #include <java/lang/InternalError.h>
39 // This is used to implement thread startup.
42 _Jv_ThreadStartFunc
*method
;
46 // This is the key used to map from the POSIX thread value back to the
47 // Java object representing the thread. The key is global to all
48 // threads, so it is ok to make it a global here.
49 pthread_key_t _Jv_ThreadKey
;
51 // This is the key used to map from the POSIX thread value back to the
52 // _Jv_Thread_t* representing the thread.
53 pthread_key_t _Jv_ThreadDataKey
;
55 // We keep a count of all non-daemon threads which are running. When
56 // this reaches zero, _Jv_ThreadWait returns.
57 static pthread_mutex_t daemon_mutex
;
58 static pthread_cond_t daemon_cond
;
59 static int non_daemon_count
;
61 // The signal to use when interrupting a thread.
62 #if defined(LINUX_THREADS) || defined(FREEBSD_THREADS)
63 // LinuxThreads (prior to glibc 2.1) usurps both SIGUSR1 and SIGUSR2.
64 // GC on FreeBSD uses both SIGUSR1 and SIGUSR2.
66 #else /* LINUX_THREADS */
68 #endif /* LINUX_THREADS */
71 // These are the flags that can appear in _Jv_Thread_t.
75 #define FLAG_START 0x01
77 #define FLAG_DAEMON 0x02
81 // Wait for the condition variable "CV" to be notified.
83 // 0: the condition was notified, or the timeout expired.
84 // _JV_NOT_OWNER: the thread does not own the mutex "MU".
85 // _JV_INTERRUPTED: the thread was interrupted. Its interrupted flag is set.
87 _Jv_CondWait (_Jv_ConditionVariable_t
*cv
, _Jv_Mutex_t
*mu
,
88 jlong millis
, jint nanos
)
90 pthread_t self
= pthread_self();
91 if (mu
->owner
!= self
)
96 if (millis
> 0 || nanos
> 0)
98 // Calculate the abstime corresponding to the timeout.
99 // Everything is in milliseconds.
101 // We use `unsigned long long' rather than jlong because our
102 // caller may pass up to Long.MAX_VALUE millis. This would
103 // overflow the range of a jlong when added to the current time.
105 unsigned long long startTime
106 = (unsigned long long)java::lang::System::currentTimeMillis();
107 unsigned long long m
= (unsigned long long)millis
+ startTime
;
108 unsigned long long seconds
= m
/ 1000;
111 if (ts
.tv_sec
< 0 || (unsigned long long)ts
.tv_sec
!= seconds
)
113 // We treat a timeout that won't fit into a struct timespec
114 // as a wait forever.
120 ts
.tv_nsec
= m
* 1000000 + (unsigned long long)nanos
;
124 _Jv_Thread_t
*current
= _Jv_ThreadCurrentData ();
125 java::lang::Thread
*current_obj
= _Jv_ThreadCurrent ();
127 pthread_mutex_lock (¤t
->wait_mutex
);
129 // Now that we hold the wait mutex, check if this thread has been
130 // interrupted already.
131 if (current_obj
->interrupt_flag
)
133 pthread_mutex_unlock (¤t
->wait_mutex
);
134 return _JV_INTERRUPTED
;
137 // Add this thread to the cv's wait set.
138 current
->next
= NULL
;
140 if (cv
->first
== NULL
)
143 for (_Jv_Thread_t
*t
= cv
->first
;; t
= t
->next
)
152 // Record the current lock depth, so it can be restored when we re-aquire it.
153 int count
= mu
->count
;
155 // Release the monitor mutex.
158 pthread_mutex_unlock (&mu
->mutex
);
161 bool done_sleeping
= false;
163 while (! done_sleeping
)
165 if (millis
== 0 && nanos
== 0)
166 r
= pthread_cond_wait (¤t
->wait_cond
, ¤t
->wait_mutex
);
168 r
= pthread_cond_timedwait (¤t
->wait_cond
, ¤t
->wait_mutex
,
171 // In older glibc's (prior to 2.1.3), the cond_wait functions may
172 // spuriously wake up on a signal. Catch that here.
174 done_sleeping
= true;
177 // Check for an interrupt *before* releasing the wait mutex.
178 jboolean interrupted
= current_obj
->interrupt_flag
;
180 pthread_mutex_unlock (¤t
->wait_mutex
);
182 // Reaquire the monitor mutex, and restore the lock count.
183 pthread_mutex_lock (&mu
->mutex
);
187 // If we were interrupted, or if a timeout occurred, remove ourself from
188 // the cv wait list now. (If we were notified normally, notify() will have
189 // already taken care of this)
190 if (r
== ETIMEDOUT
|| interrupted
)
192 _Jv_Thread_t
*prev
= NULL
;
193 for (_Jv_Thread_t
*t
= cv
->first
; t
!= NULL
; t
= t
->next
)
198 prev
->next
= t
->next
;
207 return _JV_INTERRUPTED
;
214 _Jv_CondNotify (_Jv_ConditionVariable_t
*cv
, _Jv_Mutex_t
*mu
)
216 if (_Jv_MutexCheckMonitor (mu
))
217 return _JV_NOT_OWNER
;
219 _Jv_Thread_t
*target
;
220 _Jv_Thread_t
*prev
= NULL
;
222 for (target
= cv
->first
; target
!= NULL
; target
= target
->next
)
224 pthread_mutex_lock (&target
->wait_mutex
);
226 if (target
->thread_obj
->interrupt_flag
)
228 // Don't notify a thread that has already been interrupted.
229 pthread_mutex_unlock (&target
->wait_mutex
);
234 pthread_cond_signal (&target
->wait_cond
);
235 pthread_mutex_unlock (&target
->wait_mutex
);
237 // Two concurrent notify() calls must not be delivered to the same
238 // thread, so remove the target thread from the cv wait list now.
240 cv
->first
= target
->next
;
242 prev
->next
= target
->next
;
253 _Jv_CondNotifyAll (_Jv_ConditionVariable_t
*cv
, _Jv_Mutex_t
*mu
)
255 if (_Jv_MutexCheckMonitor (mu
))
256 return _JV_NOT_OWNER
;
258 _Jv_Thread_t
*target
;
259 _Jv_Thread_t
*prev
= NULL
;
261 for (target
= cv
->first
; target
!= NULL
; target
= target
->next
)
263 pthread_mutex_lock (&target
->wait_mutex
);
264 pthread_cond_signal (&target
->wait_cond
);
265 pthread_mutex_unlock (&target
->wait_mutex
);
280 _Jv_ThreadInterrupt (_Jv_Thread_t
*data
)
282 pthread_mutex_lock (&data
->wait_mutex
);
284 // Set the thread's interrupted flag *after* aquiring its wait_mutex. This
285 // ensures that there are no races with the interrupt flag being set after
286 // the waiting thread checks it and before pthread_cond_wait is entered.
287 data
->thread_obj
->interrupt_flag
= true;
289 // Interrupt blocking system calls using a signal.
290 pthread_kill (data
->thread
, INTR
);
292 pthread_cond_signal (&data
->wait_cond
);
294 pthread_mutex_unlock (&data
->wait_mutex
);
308 sigaddset (&mask
, SIGCHLD
);
309 int c
= pthread_sigmask (SIG_BLOCK
, &mask
, NULL
);
311 JvFail (strerror (c
));
315 _Jv_InitThreads (void)
317 pthread_key_create (&_Jv_ThreadKey
, NULL
);
318 pthread_key_create (&_Jv_ThreadDataKey
, NULL
);
319 pthread_mutex_init (&daemon_mutex
, NULL
);
320 pthread_cond_init (&daemon_cond
, 0);
321 non_daemon_count
= 0;
323 // Arrange for the interrupt signal to interrupt system calls.
324 struct sigaction act
;
325 act
.sa_handler
= handle_intr
;
326 sigemptyset (&act
.sa_mask
);
328 sigaction (INTR
, &act
, NULL
);
330 // Block SIGCHLD here to ensure that any non-Java threads inherit the new
334 // Check/set the thread stack size.
335 size_t min_ss
= 32 * 1024;
337 if (sizeof (void *) == 8)
338 // Bigger default on 64-bit systems.
341 #ifdef PTHREAD_STACK_MIN
342 if (min_ss
< PTHREAD_STACK_MIN
)
343 min_ss
= PTHREAD_STACK_MIN
;
346 if (gcj::stack_size
> 0 && gcj::stack_size
< min_ss
)
347 gcj::stack_size
= min_ss
;
351 _Jv_ThreadInitData (java::lang::Thread
*obj
)
353 _Jv_Thread_t
*data
= (_Jv_Thread_t
*) _Jv_Malloc (sizeof (_Jv_Thread_t
));
355 data
->thread_obj
= obj
;
357 pthread_mutex_init (&data
->wait_mutex
, NULL
);
358 pthread_cond_init (&data
->wait_cond
, NULL
);
364 _Jv_ThreadDestroyData (_Jv_Thread_t
*data
)
366 pthread_mutex_destroy (&data
->wait_mutex
);
367 pthread_cond_destroy (&data
->wait_cond
);
368 _Jv_Free ((void *)data
);
372 _Jv_ThreadSetPriority (_Jv_Thread_t
*data
, jint prio
)
374 #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING
375 if (data
->flags
& FLAG_START
)
377 struct sched_param param
;
379 param
.sched_priority
= prio
;
380 pthread_setschedparam (data
->thread
, SCHED_OTHER
, ¶m
);
386 _Jv_ThreadRegister (_Jv_Thread_t
*data
)
388 pthread_setspecific (_Jv_ThreadKey
, data
->thread_obj
);
389 pthread_setspecific (_Jv_ThreadDataKey
, data
);
391 // glibc 2.1.3 doesn't set the value of `thread' until after start_routine
392 // is called. Since it may need to be accessed from the new thread, work
393 // around the potential race here by explicitly setting it again.
394 data
->thread
= pthread_self ();
396 # ifdef SLOW_PTHREAD_SELF
397 // Clear all self cache slots that might be needed by this thread.
399 int low_index
= SC_INDEX(&dummy
) + SC_CLEAR_MIN
;
400 int high_index
= SC_INDEX(&dummy
) + SC_CLEAR_MAX
;
401 for (int i
= low_index
; i
<= high_index
; ++i
)
403 int current_index
= i
;
404 if (current_index
< 0)
405 current_index
+= SELF_CACHE_SIZE
;
406 if (current_index
>= SELF_CACHE_SIZE
)
407 current_index
-= SELF_CACHE_SIZE
;
408 _Jv_self_cache
[current_index
].high_sp_bits
= BAD_HIGH_SP_VALUE
;
411 // Block SIGCHLD which is used in natPosixProcess.cc.
416 _Jv_ThreadUnRegister ()
418 pthread_setspecific (_Jv_ThreadKey
, NULL
);
419 pthread_setspecific (_Jv_ThreadDataKey
, NULL
);
422 // This function is called when a thread is started. We don't arrange
423 // to call the `run' method directly, because this function must
426 really_start (void *x
)
428 struct starter
*info
= (struct starter
*) x
;
430 _Jv_ThreadRegister (info
->data
);
432 info
->method (info
->data
->thread_obj
);
434 if (! (info
->data
->flags
& FLAG_DAEMON
))
436 pthread_mutex_lock (&daemon_mutex
);
438 if (! non_daemon_count
)
439 pthread_cond_signal (&daemon_cond
);
440 pthread_mutex_unlock (&daemon_mutex
);
447 _Jv_ThreadStart (java::lang::Thread
*thread
, _Jv_Thread_t
*data
,
448 _Jv_ThreadStartFunc
*meth
)
450 struct sched_param param
;
452 struct starter
*info
;
454 if (data
->flags
& FLAG_START
)
456 data
->flags
|= FLAG_START
;
458 // Block SIGCHLD which is used in natPosixProcess.cc.
459 // The current mask is inherited by the child thread.
462 param
.sched_priority
= thread
->getPriority();
464 pthread_attr_init (&attr
);
465 pthread_attr_setschedparam (&attr
, ¶m
);
466 pthread_attr_setdetachstate (&attr
, PTHREAD_CREATE_DETACHED
);
468 // Set stack size if -Xss option was given.
469 if (gcj::stack_size
> 0)
471 int e
= pthread_attr_setstacksize (&attr
, gcj::stack_size
);
473 JvFail (strerror (e
));
476 info
= (struct starter
*) _Jv_AllocBytes (sizeof (struct starter
));
480 if (! thread
->isDaemon())
482 pthread_mutex_lock (&daemon_mutex
);
484 pthread_mutex_unlock (&daemon_mutex
);
487 data
->flags
|= FLAG_DAEMON
;
488 int r
= pthread_create (&data
->thread
, &attr
, really_start
, (void *) info
);
490 pthread_attr_destroy (&attr
);
494 const char* msg
= "Cannot create additional threads";
495 throw new java::lang::OutOfMemoryError (JvNewStringUTF (msg
));
500 _Jv_ThreadWait (void)
502 pthread_mutex_lock (&daemon_mutex
);
503 if (non_daemon_count
)
504 pthread_cond_wait (&daemon_cond
, &daemon_mutex
);
505 pthread_mutex_unlock (&daemon_mutex
);
508 #if defined(SLOW_PTHREAD_SELF)
510 #include "sysdep/locks.h"
512 // Support for pthread_self() lookup cache.
513 volatile self_cache_entry _Jv_self_cache
[SELF_CACHE_SIZE
];
516 _Jv_ThreadSelf_out_of_line(volatile self_cache_entry
*sce
, size_t high_sp_bits
)
518 pthread_t self
= pthread_self();
519 sce
-> high_sp_bits
= high_sp_bits
;
525 #endif /* SLOW_PTHREAD_SELF */