1 // win32-threads.cc - interface between libjava and Win32 threads.
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2006 Free Software
6 This file is part of libgcj.
8 This software is copyrighted work licensed under the terms of the
9 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
14 // If we're using the Boehm GC, then we need to override some of the
15 // thread primitives. This is fairly gross.
20 // <windows.h> #define's STRICT, which conflicts with Modifier.h
23 #endif /* HAVE_BOEHM_GC */
27 #include <java/lang/Thread.h>
28 #include <java/lang/System.h>
36 // This is used to implement thread startup.
39 _Jv_ThreadStartFunc
*method
;
43 // Controls access to the variable below
44 static HANDLE daemon_mutex
;
45 static HANDLE daemon_cond
;
46 // Number of non-daemon threads - _Jv_ThreadWait returns when this is 0
47 static int non_daemon_count
;
49 // TLS key get Java object representing the thread
51 // TLS key to get _Jv_Thread_t* representing the thread
52 DWORD _Jv_ThreadDataKey
;
55 // These are the flags that can appear in _Jv_Thread_t.
59 #define FLAG_START 0x01
61 #define FLAG_DAEMON 0x02
67 compare_and_exchange(LONG
volatile* dest
, LONG cmp
, LONG xchg
)
69 return InterlockedCompareExchange((LONG
*) dest
, xchg
, cmp
) == cmp
;
70 // Seems like a bug in the MinGW headers that we have to do this cast.
74 // Condition variables.
77 // we do lazy creation of Events since CreateEvent() is insanely
78 // expensive, and because the rest of libgcj will call _Jv_CondInit
79 // when only a mutex is needed.
82 ensure_condvar_initialized(_Jv_ConditionVariable_t
*cv
)
86 cv
->ev
[0] = CreateEvent (NULL
, 0, 0, NULL
);
87 if (cv
->ev
[0] == 0) JvFail("CreateEvent() failed");
89 cv
->ev
[1] = CreateEvent (NULL
, 1, 0, NULL
);
90 if (cv
->ev
[1] == 0) JvFail("CreateEvent() failed");
95 ensure_interrupt_event_initialized(HANDLE
& rhEvent
)
99 rhEvent
= CreateEvent (NULL
, 0, 0, NULL
);
100 if (!rhEvent
) JvFail("CreateEvent() failed");
104 // Reimplementation of the general algorithm described at
105 // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html (isomorphic to
106 // 3.2, not a cut-and-paste).
109 _Jv_CondWait(_Jv_ConditionVariable_t
*cv
, _Jv_Mutex_t
*mu
, jlong millis
, jint nanos
)
111 if (mu
->owner
!= GetCurrentThreadId ( ))
112 return _JV_NOT_OWNER
;
114 _Jv_Thread_t
*current
= _Jv_ThreadCurrentData ();
115 java::lang::Thread
*current_obj
= _Jv_ThreadCurrent ();
117 // Now that we hold the interrupt mutex, check if this thread has been
118 // interrupted already.
119 EnterCriticalSection (¤t
->interrupt_mutex
);
120 ensure_interrupt_event_initialized (current
->interrupt_event
);
121 jboolean interrupted
= current_obj
->interrupt_flag
;
122 LeaveCriticalSection (¤t
->interrupt_mutex
);
126 return _JV_INTERRUPTED
;
129 EnterCriticalSection (&cv
->count_mutex
);
130 ensure_condvar_initialized (cv
);
132 LeaveCriticalSection (&cv
->count_mutex
);
135 if ((millis
== 0) && (nanos
> 0)) time
= 1;
136 else if (millis
== 0) time
= INFINITE
;
139 // Record the current lock depth, so it can be restored
140 // when we reacquire it.
141 int count
= mu
->refcount
;
142 int curcount
= count
;
144 // Call _Jv_MutexUnlock repeatedly until this thread
145 // has completely released the monitor.
148 _Jv_MutexUnlock (mu
);
152 // Set up our array of three events:
153 // - the auto-reset event (for notify())
154 // - the manual-reset event (for notifyAll())
155 // - the interrupt event (for interrupt())
156 // We wait for any one of these to be signaled.
160 arh
[2] = current
->interrupt_event
;
161 DWORD rval
= WaitForMultipleObjects (3, arh
, 0, time
);
163 EnterCriticalSection (¤t
->interrupt_mutex
);
165 // If we were unblocked by the third event (our thread's interrupt
166 // event), set the thread's interrupt flag. I think this sanity
167 // check guards against someone resetting our interrupt flag
168 // in the time between when interrupt_mutex is released in
169 // _Jv_ThreadInterrupt and the interval of time between the
170 // WaitForMultipleObjects call we just made and our acquisition
171 // of interrupt_mutex.
172 if (rval
== (WAIT_OBJECT_0
+ 2))
173 current_obj
->interrupt_flag
= true;
175 interrupted
= current_obj
->interrupt_flag
;
176 LeaveCriticalSection (¤t
->interrupt_mutex
);
178 EnterCriticalSection(&cv
->count_mutex
);
180 // If we were unblocked by the second event (the broadcast one)
181 // and nobody is left, then reset the event.
182 int last_waiter
= (rval
== (WAIT_OBJECT_0
+ 1)) && (cv
->blocked_count
== 0);
183 LeaveCriticalSection(&cv
->count_mutex
);
186 ResetEvent (cv
->ev
[1]);
188 // Call _Jv_MutexLock repeatedly until the mutex's refcount is the
189 // same as before we originally released it.
190 while (curcount
< count
)
196 return interrupted
? _JV_INTERRUPTED
: 0;
200 _Jv_CondInit (_Jv_ConditionVariable_t
*cv
)
202 // we do lazy creation of Events since CreateEvent() is insanely expensive
204 InitializeCriticalSection (&cv
->count_mutex
);
205 cv
->blocked_count
= 0;
209 _Jv_CondDestroy (_Jv_ConditionVariable_t
*cv
)
213 CloseHandle (cv
->ev
[0]);
214 CloseHandle (cv
->ev
[1]);
219 DeleteCriticalSection (&cv
->count_mutex
);
223 _Jv_CondNotify (_Jv_ConditionVariable_t
*cv
, _Jv_Mutex_t
*mu
)
225 if (mu
->owner
!= GetCurrentThreadId ( ))
226 return _JV_NOT_OWNER
;
228 EnterCriticalSection (&cv
->count_mutex
);
229 ensure_condvar_initialized (cv
);
230 int somebody_is_blocked
= cv
->blocked_count
> 0;
231 LeaveCriticalSection (&cv
->count_mutex
);
233 if (somebody_is_blocked
)
234 SetEvent (cv
->ev
[0]);
240 _Jv_CondNotifyAll (_Jv_ConditionVariable_t
*cv
, _Jv_Mutex_t
*mu
)
242 if (mu
->owner
!= GetCurrentThreadId ( ))
243 return _JV_NOT_OWNER
;
245 EnterCriticalSection (&cv
->count_mutex
);
246 ensure_condvar_initialized (cv
);
247 int somebody_is_blocked
= cv
->blocked_count
> 0;
248 LeaveCriticalSection (&cv
->count_mutex
);
250 if (somebody_is_blocked
)
251 SetEvent (cv
->ev
[1]);
261 _Jv_InitThreads (void)
263 _Jv_ThreadKey
= TlsAlloc();
264 _Jv_ThreadDataKey
= TlsAlloc();
265 daemon_mutex
= CreateMutex (NULL
, 0, NULL
);
266 daemon_cond
= CreateEvent (NULL
, 1, 0, NULL
);
267 non_daemon_count
= 0;
271 _Jv_ThreadInitData (java::lang::Thread
* obj
)
273 _Jv_Thread_t
*data
= (_Jv_Thread_t
*)_Jv_Malloc(sizeof(_Jv_Thread_t
));
276 data
->thread_obj
= obj
;
277 data
->interrupt_event
= 0;
278 InitializeCriticalSection (&data
->interrupt_mutex
);
284 _Jv_ThreadDestroyData (_Jv_Thread_t
*data
)
286 DeleteCriticalSection (&data
->interrupt_mutex
);
287 if (data
->interrupt_event
)
288 CloseHandle(data
->interrupt_event
);
289 CloseHandle(data
->handle
);
294 _Jv_ThreadSetPriority (_Jv_Thread_t
*data
, jint prio
)
296 int actual
= THREAD_PRIORITY_NORMAL
;
298 if (data
->flags
& FLAG_START
)
303 actual
= THREAD_PRIORITY_TIME_CRITICAL
;
306 actual
= THREAD_PRIORITY_HIGHEST
;
310 actual
= THREAD_PRIORITY_ABOVE_NORMAL
;
314 actual
= THREAD_PRIORITY_NORMAL
;
318 actual
= THREAD_PRIORITY_BELOW_NORMAL
;
321 actual
= THREAD_PRIORITY_LOWEST
;
324 actual
= THREAD_PRIORITY_IDLE
;
327 SetThreadPriority(data
->handle
, actual
);
332 _Jv_ThreadRegister (_Jv_Thread_t
*data
)
334 TlsSetValue (_Jv_ThreadKey
, data
->thread_obj
);
335 TlsSetValue (_Jv_ThreadDataKey
, data
);
339 _Jv_ThreadUnRegister ()
341 TlsSetValue (_Jv_ThreadKey
, NULL
);
342 TlsSetValue (_Jv_ThreadDataKey
, NULL
);
345 // This function is called when a thread is started. We don't arrange
346 // to call the `run' method directly, because this function must
349 really_start (void* x
)
351 struct starter
*info
= (struct starter
*) x
;
353 _Jv_ThreadRegister (info
->data
);
355 info
->method (info
->data
->thread_obj
);
357 if (! (info
->data
->flags
& FLAG_DAEMON
))
359 WaitForSingleObject (daemon_mutex
, INFINITE
);
361 if (! non_daemon_count
)
362 SetEvent (daemon_cond
);
363 ReleaseMutex (daemon_mutex
);
370 _Jv_ThreadStart (java::lang::Thread
*thread
, _Jv_Thread_t
*data
, _Jv_ThreadStartFunc
*meth
)
373 struct starter
*info
;
375 // Do nothing if thread has already started
376 if (data
->flags
& FLAG_START
)
378 data
->flags
|= FLAG_START
;
380 info
= (struct starter
*) _Jv_AllocBytes (sizeof (struct starter
));
384 if (! thread
->isDaemon ())
386 WaitForSingleObject (daemon_mutex
, INFINITE
);
388 ReleaseMutex (daemon_mutex
);
391 data
->flags
|= FLAG_DAEMON
;
393 data
->handle
= GC_CreateThread(NULL
, 0, really_start
, info
, 0, &id
);
394 _Jv_ThreadSetPriority(data
, thread
->getPriority());
398 _Jv_ThreadWait (void)
400 WaitForSingleObject (daemon_mutex
, INFINITE
);
401 if (non_daemon_count
)
403 ReleaseMutex (daemon_mutex
);
404 WaitForSingleObject (daemon_cond
, INFINITE
);
413 _Jv_Win32GetInterruptEvent (void)
415 _Jv_Thread_t
*current
= _Jv_ThreadCurrentData ();
416 EnterCriticalSection (¤t
->interrupt_mutex
);
417 ensure_interrupt_event_initialized (current
->interrupt_event
);
418 HANDLE hEvent
= current
->interrupt_event
;
419 LeaveCriticalSection (¤t
->interrupt_mutex
);
424 _Jv_ThreadInterrupt (_Jv_Thread_t
*data
)
426 EnterCriticalSection (&data
->interrupt_mutex
);
427 ensure_interrupt_event_initialized (data
->interrupt_event
);
428 data
->thread_obj
->interrupt_flag
= true;
429 SetEvent (data
->interrupt_event
);
430 LeaveCriticalSection (&data
->interrupt_mutex
);
433 // park() / unpark() support
438 // We initialize our critical section, but not our event.
439 InitializeCriticalSection (&cs
);
444 ParkHelper::init_event()
446 EnterCriticalSection (&cs
);
449 // Create an auto-reset event.
450 event
= CreateEvent(NULL
, 0, 0, NULL
);
451 if (!event
) JvFail("CreateEvent() failed");
453 LeaveCriticalSection (&cs
);
457 ParkHelper::deactivate ()
459 permit
= ::java::lang::Thread::THREAD_PARK_DEAD
;
463 ParkHelper::destroy()
465 if (event
) CloseHandle (event
);
466 DeleteCriticalSection (&cs
);
470 * Releases the block on a thread created by _Jv_ThreadPark(). This
471 * method can also be used to terminate a blockage caused by a prior
472 * call to park. This operation is unsafe, as the thread must be
473 * guaranteed to be live.
475 * @param thread the thread to unblock.
478 ParkHelper::unpark ()
480 using namespace ::java::lang
;
481 LONG
volatile* ptr
= &permit
;
483 // If this thread is in state RUNNING, give it a permit and return
485 if (compare_and_exchange
486 (ptr
, Thread::THREAD_PARK_RUNNING
, Thread::THREAD_PARK_PERMIT
))
489 // If this thread is parked, put it into state RUNNING and send it a
491 if (compare_and_exchange
492 (ptr
, Thread::THREAD_PARK_PARKED
, Thread::THREAD_PARK_RUNNING
))
500 * Blocks the thread until a matching _Jv_ThreadUnpark() occurs, the
501 * thread is interrupted or the optional timeout expires. If an
502 * unpark call has already occurred, this also counts. A timeout
503 * value of zero is defined as no timeout. When isAbsolute is true,
504 * the timeout is in milliseconds relative to the epoch. Otherwise,
505 * the value is the number of nanoseconds which must occur before
506 * timeout. This call may also return spuriously (i.e. for no
509 * @param isAbsolute true if the timeout is specified in milliseconds from
511 * @param time either the number of nanoseconds to wait, or a time in
512 * milliseconds from the epoch to wait for.
515 ParkHelper::park (jboolean isAbsolute
, jlong time
)
517 using namespace ::java::lang
;
518 LONG
volatile* ptr
= &permit
;
520 // If we have a permit, return immediately.
521 if (compare_and_exchange
522 (ptr
, Thread::THREAD_PARK_PERMIT
, Thread::THREAD_PARK_RUNNING
))
525 // Determine the number of milliseconds to wait.
526 jlong millis
= 0, nanos
= 0;
532 millis
= time
- ::java::lang::System::currentTimeMillis();
543 millis
+= nanos
/ 1000000;
546 // ...otherwise, we'll block indefinitely.
550 if (millis
< 0) return;
551 // Can this ever happen?
553 if (compare_and_exchange
554 (ptr
, Thread::THREAD_PARK_RUNNING
, Thread::THREAD_PARK_PARKED
))
558 DWORD timeout
= millis
==0 ? INFINITE
: (DWORD
) millis
;
559 WaitForSingleObject (event
, timeout
);
561 // If we were unparked by some other thread, this will already
562 // be in state THREAD_PARK_RUNNING. If we timed out, we have to
565 (ptr
, Thread::THREAD_PARK_PARKED
, Thread::THREAD_PARK_RUNNING
);