win32-threads.cc 13.7 KB
Newer Older
Tom Tromey committed
1 2
// win32-threads.cc - interface between libjava and Win32 threads.

3
/* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2006 Free Software
4
   Foundation, Inc.
Tom Tromey committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

   This file is part of libgcj.

This software is copyrighted work licensed under the terms of the
Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
details.  */

#include <config.h>

// If we're using the Boehm GC, then we need to override some of the
// thread primitives.  This is fairly gross.
#ifdef HAVE_BOEHM_GC
extern "C"
{
#include <gc.h>
20 21
// <windows.h> #define's STRICT, which conflicts with Modifier.h
#undef STRICT
Tom Tromey committed
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
};
#endif /* HAVE_BOEHM_GC */

#include <gcj/cni.h>
#include <jvm.h>
#include <java/lang/Thread.h>
#include <java/lang/System.h>

#include <errno.h>

#ifndef ETIMEDOUT
#define ETIMEDOUT 116
#endif

// This is used to implement thread startup.
struct starter
{
  _Jv_ThreadStartFunc *method;
  _Jv_Thread_t *data;
};

// Controls access to the variable below
static HANDLE daemon_mutex;
static HANDLE daemon_cond;
// Number of non-daemon threads - _Jv_ThreadWait returns when this is 0
static int non_daemon_count;

// TLS key get Java object representing the thread
DWORD _Jv_ThreadKey;
// TLS key to get _Jv_Thread_t* representing the thread
DWORD _Jv_ThreadDataKey;

//
// These are the flags that can appear in _Jv_Thread_t.
//

// Thread started.
#define FLAG_START   0x01
// Thread is daemon.
#define FLAG_DAEMON  0x02

//
64 65 66 67 68 69 70 71 72 73
// Helper
//
inline bool
compare_and_exchange(LONG volatile* dest, LONG cmp, LONG xchg)
{
  return InterlockedCompareExchange((LONG*) dest, xchg, cmp) == cmp;
    // Seems like a bug in the MinGW headers that we have to do this cast.
}

//
Tom Tromey committed
74 75 76
// Condition variables.
//

Adam Megacz committed
77 78 79 80 81 82 83
// we do lazy creation of Events since CreateEvent() is insanely
// expensive, and because the rest of libgcj will call _Jv_CondInit
// when only a mutex is needed.

inline void
ensure_condvar_initialized(_Jv_ConditionVariable_t *cv)
{
84 85 86 87 88 89 90 91
  if (cv->ev[0] == 0)
    {
      cv->ev[0] = CreateEvent (NULL, 0, 0, NULL);
      if (cv->ev[0] == 0) JvFail("CreateEvent() failed");

      cv->ev[1] = CreateEvent (NULL, 1, 0, NULL);
      if (cv->ev[1] == 0) JvFail("CreateEvent() failed");
    }
Adam Megacz committed
92 93
}

94 95 96 97 98 99 100 101 102 103
inline void
ensure_interrupt_event_initialized(HANDLE& rhEvent)
{
  if (!rhEvent)
    {
      rhEvent = CreateEvent (NULL, 0, 0, NULL);
      if (!rhEvent) JvFail("CreateEvent() failed");
    }
}

Adam Megacz committed
104 105 106 107
// Reimplementation of the general algorithm described at
// http://www.cs.wustl.edu/~schmidt/win32-cv-1.html (isomorphic to
// 3.2, not a cut-and-paste).

Tom Tromey committed
108
int
Adam Megacz committed
109
_Jv_CondWait(_Jv_ConditionVariable_t *cv, _Jv_Mutex_t *mu, jlong millis, jint nanos)
Tom Tromey committed
110
{
111 112
  if (mu->owner != GetCurrentThreadId ( ))
    return _JV_NOT_OWNER;
Tom Tromey committed
113

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
  _Jv_Thread_t *current = _Jv_ThreadCurrentData ();
  java::lang::Thread *current_obj = _Jv_ThreadCurrent ();

  // Now that we hold the interrupt mutex, check if this thread has been 
  // interrupted already.
  EnterCriticalSection (&current->interrupt_mutex);
  ensure_interrupt_event_initialized (current->interrupt_event);
  jboolean interrupted = current_obj->interrupt_flag;
  LeaveCriticalSection (&current->interrupt_mutex);

  if (interrupted)
    {
      return _JV_INTERRUPTED;
    }

129 130
  EnterCriticalSection (&cv->count_mutex);
  ensure_condvar_initialized (cv);
Adam Megacz committed
131
  cv->blocked_count++;
132
  LeaveCriticalSection (&cv->count_mutex);
Adam Megacz committed
133 134 135 136 137

  DWORD time;
  if ((millis == 0) && (nanos > 0)) time = 1;
  else if (millis == 0) time = INFINITE;
  else time = millis;
138

139 140 141 142 143 144 145 146 147 148 149 150
  // Record the current lock depth, so it can be restored
  // when we reacquire it.
  int count = mu->refcount;
  int curcount = count;

  // Call _Jv_MutexUnlock repeatedly until this thread
  // has completely released the monitor.
  while (curcount > 0)
    {  
      _Jv_MutexUnlock (mu);
      --curcount;
    }
Tom Tromey committed
151

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
  // Set up our array of three events:
  // - the auto-reset event (for notify())
  // - the manual-reset event (for notifyAll())
  // - the interrupt event (for interrupt())
  // We wait for any one of these to be signaled.
  HANDLE arh[3];
  arh[0] = cv->ev[0];
  arh[1] = cv->ev[1];
  arh[2] = current->interrupt_event;
  DWORD rval = WaitForMultipleObjects (3, arh, 0, time);

  EnterCriticalSection (&current->interrupt_mutex);

  // If we were unblocked by the third event (our thread's interrupt
  // event), set the thread's interrupt flag. I think this sanity
  // check guards against someone resetting our interrupt flag
  // in the time between when interrupt_mutex is released in
  // _Jv_ThreadInterrupt and the interval of time between the
  // WaitForMultipleObjects call we just made and our acquisition
  // of interrupt_mutex.
  if (rval == (WAIT_OBJECT_0 + 2))
    current_obj->interrupt_flag = true;
    
  interrupted = current_obj->interrupt_flag;
  LeaveCriticalSection (&current->interrupt_mutex);
Adam Megacz committed
177 178 179

  EnterCriticalSection(&cv->count_mutex);
  cv->blocked_count--;
180 181 182
  // If we were unblocked by the second event (the broadcast one)
  // and nobody is left, then reset the event.
  int last_waiter = (rval == (WAIT_OBJECT_0 + 1)) && (cv->blocked_count == 0);
Adam Megacz committed
183 184
  LeaveCriticalSection(&cv->count_mutex);

185 186
  if (last_waiter)
    ResetEvent (cv->ev[1]);
Tom Tromey committed
187

188 189 190 191 192 193 194
  // Call _Jv_MutexLock repeatedly until the mutex's refcount is the
  // same as before we originally released it.
  while (curcount < count)
    {  
      _Jv_MutexLock (mu);
      ++curcount;
    }
195 196
  
  return interrupted ? _JV_INTERRUPTED : 0;
Tom Tromey committed
197 198
}

Adam Megacz committed
199 200 201 202 203
void
_Jv_CondInit (_Jv_ConditionVariable_t *cv)
{
  // we do lazy creation of Events since CreateEvent() is insanely expensive
  cv->ev[0] = 0;
204
  InitializeCriticalSection (&cv->count_mutex);
Adam Megacz committed
205 206 207 208 209 210
  cv->blocked_count = 0;
}

void
_Jv_CondDestroy (_Jv_ConditionVariable_t *cv)
{
211 212 213 214 215 216 217 218 219
  if (cv->ev[0] != 0)
    {
      CloseHandle (cv->ev[0]);
      CloseHandle (cv->ev[1]);

      cv->ev[0] = 0;
    }

  DeleteCriticalSection (&cv->count_mutex);
Adam Megacz committed
220
}
Tom Tromey committed
221 222

int
223
_Jv_CondNotify (_Jv_ConditionVariable_t *cv, _Jv_Mutex_t *mu)
Tom Tromey committed
224
{
225 226 227 228 229
  if (mu->owner != GetCurrentThreadId ( ))
    return _JV_NOT_OWNER;

  EnterCriticalSection (&cv->count_mutex);
  ensure_condvar_initialized (cv);
Adam Megacz committed
230
  int somebody_is_blocked = cv->blocked_count > 0;
231 232 233 234
  LeaveCriticalSection (&cv->count_mutex);

  if (somebody_is_blocked)
    SetEvent (cv->ev[0]);
Tom Tromey committed
235

236
  return 0;
Adam Megacz committed
237
}
Tom Tromey committed
238

Adam Megacz committed
239
int
240
_Jv_CondNotifyAll (_Jv_ConditionVariable_t *cv, _Jv_Mutex_t *mu)
Adam Megacz committed
241
{
242 243 244 245 246
  if (mu->owner != GetCurrentThreadId ( ))
    return _JV_NOT_OWNER;

  EnterCriticalSection (&cv->count_mutex);
  ensure_condvar_initialized (cv);
Adam Megacz committed
247
  int somebody_is_blocked = cv->blocked_count > 0;
248
  LeaveCriticalSection (&cv->count_mutex);
Adam Megacz committed
249

250 251 252 253
  if (somebody_is_blocked)
    SetEvent (cv->ev[1]);

  return 0;
Tom Tromey committed
254 255 256 257 258 259 260 261 262 263 264
}

//
// Threads.
//

void
_Jv_InitThreads (void)
{
  _Jv_ThreadKey = TlsAlloc();
  _Jv_ThreadDataKey = TlsAlloc();
265 266
  daemon_mutex = CreateMutex (NULL, 0, NULL);
  daemon_cond = CreateEvent (NULL, 1, 0, NULL);
Tom Tromey committed
267 268 269
  non_daemon_count = 0;
}

Bryce McKinlay committed
270
_Jv_Thread_t *
271
_Jv_ThreadInitData (java::lang::Thread* obj)
Tom Tromey committed
272
{
273
  _Jv_Thread_t *data = (_Jv_Thread_t*)_Jv_Malloc(sizeof(_Jv_Thread_t));
Bryce McKinlay committed
274
  data->flags = 0;
275
  data->handle = 0;
276
  data->thread_obj = obj;
277 278
  data->interrupt_event = 0;
  InitializeCriticalSection (&data->interrupt_mutex);
Tom Tromey committed
279

Bryce McKinlay committed
280 281
  return data;
}
Tom Tromey committed
282

Bryce McKinlay committed
283 284 285
void
_Jv_ThreadDestroyData (_Jv_Thread_t *data)
{
286 287 288
  DeleteCriticalSection (&data->interrupt_mutex);
  if (data->interrupt_event)
    CloseHandle(data->interrupt_event);
289
  CloseHandle(data->handle);
290
  _Jv_Free(data);
Tom Tromey committed
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
}

void
_Jv_ThreadSetPriority (_Jv_Thread_t *data, jint prio)
{
  int actual = THREAD_PRIORITY_NORMAL;

  if (data->flags & FLAG_START)
    {
      switch (prio)
        {
          case 10:
            actual = THREAD_PRIORITY_TIME_CRITICAL;
            break;
          case 9:
            actual = THREAD_PRIORITY_HIGHEST;
            break;
          case 8:
          case 7:
            actual = THREAD_PRIORITY_ABOVE_NORMAL;
            break;
          case 6:
          case 5:
            actual = THREAD_PRIORITY_NORMAL;
            break;
          case 4:
          case 3:
            actual = THREAD_PRIORITY_BELOW_NORMAL;
            break;
          case 2:
            actual = THREAD_PRIORITY_LOWEST;
            break;
          case 1:
            actual = THREAD_PRIORITY_IDLE;
            break;
        }
      SetThreadPriority(data->handle, actual);
    }
}

331 332 333 334 335 336 337 338 339 340 341 342 343 344
void
_Jv_ThreadRegister (_Jv_Thread_t *data)
{
  TlsSetValue (_Jv_ThreadKey, data->thread_obj);
  TlsSetValue (_Jv_ThreadDataKey, data);
}

void
_Jv_ThreadUnRegister ()
{
  TlsSetValue (_Jv_ThreadKey, NULL);
  TlsSetValue (_Jv_ThreadDataKey, NULL);
}

Tom Tromey committed
345 346 347
// This function is called when a thread is started.  We don't arrange
// to call the `run' method directly, because this function must
// return a value.
Adam Megacz committed
348
static DWORD WINAPI
Tom Tromey committed
349 350 351 352
really_start (void* x)
{
  struct starter *info = (struct starter *) x;

353 354 355
  _Jv_ThreadRegister (info->data);

  info->method (info->data->thread_obj);
Tom Tromey committed
356 357 358 359 360 361

  if (! (info->data->flags & FLAG_DAEMON))
    {
      WaitForSingleObject (daemon_mutex, INFINITE);
      non_daemon_count--;
      if (! non_daemon_count)
362
        SetEvent (daemon_cond);
Tom Tromey committed
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
      ReleaseMutex (daemon_mutex);
    }

  return 0;
}

void
_Jv_ThreadStart (java::lang::Thread *thread, _Jv_Thread_t *data, _Jv_ThreadStartFunc *meth)
{
  DWORD id;
  struct starter *info;

  // Do nothing if thread has already started
  if (data->flags & FLAG_START)
    return;
  data->flags |= FLAG_START;

  info = (struct starter *) _Jv_AllocBytes (sizeof (struct starter));
  info->method = meth;
  info->data = data;

  if (! thread->isDaemon ())
    {
      WaitForSingleObject (daemon_mutex, INFINITE);
      non_daemon_count++;
      ReleaseMutex (daemon_mutex);
    }
  else
    data->flags |= FLAG_DAEMON;

393
  data->handle = GC_CreateThread(NULL, 0, really_start, info, 0, &id);
Tom Tromey committed
394 395 396 397 398 399
  _Jv_ThreadSetPriority(data, thread->getPriority());
}

void
_Jv_ThreadWait (void)
{
400 401 402 403 404 405
  WaitForSingleObject (daemon_mutex, INFINITE);
  if (non_daemon_count)
    {
      ReleaseMutex (daemon_mutex);
      WaitForSingleObject (daemon_cond, INFINITE);
    }
Tom Tromey committed
406 407
}

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
//
// Interrupt support
//

HANDLE
_Jv_Win32GetInterruptEvent (void)
{
  _Jv_Thread_t *current = _Jv_ThreadCurrentData ();
  EnterCriticalSection (&current->interrupt_mutex);
  ensure_interrupt_event_initialized (current->interrupt_event);
  HANDLE hEvent = current->interrupt_event;
  LeaveCriticalSection (&current->interrupt_mutex);
  return hEvent;
}

Tom Tromey committed
423 424 425
void
_Jv_ThreadInterrupt (_Jv_Thread_t *data)
{
426 427 428 429 430
  EnterCriticalSection (&data->interrupt_mutex);
  ensure_interrupt_event_initialized (data->interrupt_event);
  data->thread_obj->interrupt_flag = true;
  SetEvent (data->interrupt_event);
  LeaveCriticalSection (&data->interrupt_mutex);
Tom Tromey committed
431
}
432

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
// park() / unpark() support

void
ParkHelper::init ()
{
  // We initialize our critical section, but not our event.
  InitializeCriticalSection (&cs);
  event = NULL;
}

void
ParkHelper::init_event()
{
  EnterCriticalSection (&cs);
  if (!event)
    {
      // Create an auto-reset event.
      event = CreateEvent(NULL, 0, 0, NULL);
      if (!event) JvFail("CreateEvent() failed");
    }
  LeaveCriticalSection (&cs);
}

void
ParkHelper::deactivate ()
{
  permit = ::java::lang::Thread::THREAD_PARK_DEAD;
}

void
ParkHelper::destroy()
{
  if (event) CloseHandle (event);
  DeleteCriticalSection (&cs);
}

/**
 * Releases the block on a thread created by _Jv_ThreadPark().  This
 * method can also be used to terminate a blockage caused by a prior
 * call to park.  This operation is unsafe, as the thread must be
 * guaranteed to be live.
 *
 * @param thread the thread to unblock.
 */
void
ParkHelper::unpark ()
{
  using namespace ::java::lang;
  LONG volatile* ptr = &permit;

  // If this thread is in state RUNNING, give it a permit and return
  // immediately.
  if (compare_and_exchange
      (ptr, Thread::THREAD_PARK_RUNNING, Thread::THREAD_PARK_PERMIT))
    return;
  
  // If this thread is parked, put it into state RUNNING and send it a
  // signal.
  if (compare_and_exchange 
      (ptr, Thread::THREAD_PARK_PARKED, Thread::THREAD_PARK_RUNNING))
    {
      init_event ();
      SetEvent (event);
    }
}

/**
 * Blocks the thread until a matching _Jv_ThreadUnpark() occurs, the
 * thread is interrupted or the optional timeout expires.  If an
 * unpark call has already occurred, this also counts.  A timeout
 * value of zero is defined as no timeout.  When isAbsolute is true,
 * the timeout is in milliseconds relative to the epoch.  Otherwise,
 * the value is the number of nanoseconds which must occur before
 * timeout.  This call may also return spuriously (i.e.  for no
 * apparent reason).
 *
 * @param isAbsolute true if the timeout is specified in milliseconds from
 *                   the epoch.
 * @param time either the number of nanoseconds to wait, or a time in
 *             milliseconds from the epoch to wait for.
 */
void
ParkHelper::park (jboolean isAbsolute, jlong time)
{
  using namespace ::java::lang;
  LONG volatile* ptr = &permit;

  // If we have a permit, return immediately.
  if (compare_and_exchange 
      (ptr, Thread::THREAD_PARK_PERMIT, Thread::THREAD_PARK_RUNNING))
    return;

  // Determine the number of milliseconds to wait.
  jlong millis = 0, nanos = 0;
  
  if (time)
    {
      if (isAbsolute)
	{
	  millis = time - ::java::lang::System::currentTimeMillis();
	  nanos = 0;
	}
      else
	{
	  millis = 0;
	  nanos = time;
	}
	
      if (nanos)
        {
          millis += nanos / 1000000;
          if (millis == 0)
            millis = 1;
            // ...otherwise, we'll block indefinitely.
        }
    }
    
  if (millis < 0) return;
      // Can this ever happen?
      
  if (compare_and_exchange 
      (ptr, Thread::THREAD_PARK_RUNNING, Thread::THREAD_PARK_PARKED))
    {
      init_event();
      
      DWORD timeout = millis==0 ? INFINITE : (DWORD) millis;
      WaitForSingleObject (event, timeout);
      
      // If we were unparked by some other thread, this will already
      // be in state THREAD_PARK_RUNNING.  If we timed out, we have to
      // do it ourself.
      compare_and_exchange 
	(ptr, Thread::THREAD_PARK_PARKED, Thread::THREAD_PARK_RUNNING);
    }
}