win32-threads.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. // win32-threads.cc - interface between libjava and Win32 threads.
  2. /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2006 Free Software
  3. Foundation, Inc.
  4. This file is part of libgcj.
  5. This software is copyrighted work licensed under the terms of the
  6. Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
  7. details. */
  8. #include <config.h>
  9. // If we're using the Boehm GC, then we need to override some of the
  10. // thread primitives. This is fairly gross.
  11. #ifdef HAVE_BOEHM_GC
  12. extern "C"
  13. {
  14. #include <gc.h>
  15. // <windows.h> #define's STRICT, which conflicts with Modifier.h
  16. #undef STRICT
  17. };
  18. #endif /* HAVE_BOEHM_GC */
  19. #include <gcj/cni.h>
  20. #include <jvm.h>
  21. #include <java/lang/Thread.h>
  22. #include <java/lang/System.h>
  23. #include <errno.h>
  24. #ifndef ETIMEDOUT
  25. #define ETIMEDOUT 116
  26. #endif
  27. // This is used to implement thread startup.
  28. struct starter
  29. {
  30. _Jv_ThreadStartFunc *method;
  31. _Jv_Thread_t *data;
  32. };
  33. // Controls access to the variable below
  34. static HANDLE daemon_mutex;
  35. static HANDLE daemon_cond;
  36. // Number of non-daemon threads - _Jv_ThreadWait returns when this is 0
  37. static int non_daemon_count;
  38. // TLS key get Java object representing the thread
  39. DWORD _Jv_ThreadKey;
  40. // TLS key to get _Jv_Thread_t* representing the thread
  41. DWORD _Jv_ThreadDataKey;
  42. //
  43. // These are the flags that can appear in _Jv_Thread_t.
  44. //
  45. // Thread started.
  46. #define FLAG_START 0x01
  47. // Thread is daemon.
  48. #define FLAG_DAEMON 0x02
  49. //
  50. // Helper
  51. //
  52. inline bool
  53. compare_and_exchange(LONG volatile* dest, LONG cmp, LONG xchg)
  54. {
  55. return InterlockedCompareExchange((LONG*) dest, xchg, cmp) == cmp;
  56. // Seems like a bug in the MinGW headers that we have to do this cast.
  57. }
  58. //
  59. // Condition variables.
  60. //
  61. // we do lazy creation of Events since CreateEvent() is insanely
  62. // expensive, and because the rest of libgcj will call _Jv_CondInit
  63. // when only a mutex is needed.
  64. inline void
  65. ensure_condvar_initialized(_Jv_ConditionVariable_t *cv)
  66. {
  67. if (cv->ev[0] == 0)
  68. {
  69. cv->ev[0] = CreateEvent (NULL, 0, 0, NULL);
  70. if (cv->ev[0] == 0) JvFail("CreateEvent() failed");
  71. cv->ev[1] = CreateEvent (NULL, 1, 0, NULL);
  72. if (cv->ev[1] == 0) JvFail("CreateEvent() failed");
  73. }
  74. }
  75. inline void
  76. ensure_interrupt_event_initialized(HANDLE& rhEvent)
  77. {
  78. if (!rhEvent)
  79. {
  80. rhEvent = CreateEvent (NULL, 0, 0, NULL);
  81. if (!rhEvent) JvFail("CreateEvent() failed");
  82. }
  83. }
  84. // Reimplementation of the general algorithm described at
  85. // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html (isomorphic to
  86. // 3.2, not a cut-and-paste).
  87. int
  88. _Jv_CondWait(_Jv_ConditionVariable_t *cv, _Jv_Mutex_t *mu, jlong millis, jint nanos)
  89. {
  90. if (mu->owner != GetCurrentThreadId ( ))
  91. return _JV_NOT_OWNER;
  92. _Jv_Thread_t *current = _Jv_ThreadCurrentData ();
  93. java::lang::Thread *current_obj = _Jv_ThreadCurrent ();
  94. // Now that we hold the interrupt mutex, check if this thread has been
  95. // interrupted already.
  96. EnterCriticalSection (&current->interrupt_mutex);
  97. ensure_interrupt_event_initialized (current->interrupt_event);
  98. jboolean interrupted = current_obj->interrupt_flag;
  99. LeaveCriticalSection (&current->interrupt_mutex);
  100. if (interrupted)
  101. {
  102. return _JV_INTERRUPTED;
  103. }
  104. EnterCriticalSection (&cv->count_mutex);
  105. ensure_condvar_initialized (cv);
  106. cv->blocked_count++;
  107. LeaveCriticalSection (&cv->count_mutex);
  108. DWORD time;
  109. if ((millis == 0) && (nanos > 0)) time = 1;
  110. else if (millis == 0) time = INFINITE;
  111. else time = millis;
  112. // Record the current lock depth, so it can be restored
  113. // when we reacquire it.
  114. int count = mu->refcount;
  115. int curcount = count;
  116. // Call _Jv_MutexUnlock repeatedly until this thread
  117. // has completely released the monitor.
  118. while (curcount > 0)
  119. {
  120. _Jv_MutexUnlock (mu);
  121. --curcount;
  122. }
  123. // Set up our array of three events:
  124. // - the auto-reset event (for notify())
  125. // - the manual-reset event (for notifyAll())
  126. // - the interrupt event (for interrupt())
  127. // We wait for any one of these to be signaled.
  128. HANDLE arh[3];
  129. arh[0] = cv->ev[0];
  130. arh[1] = cv->ev[1];
  131. arh[2] = current->interrupt_event;
  132. DWORD rval = WaitForMultipleObjects (3, arh, 0, time);
  133. EnterCriticalSection (&current->interrupt_mutex);
  134. // If we were unblocked by the third event (our thread's interrupt
  135. // event), set the thread's interrupt flag. I think this sanity
  136. // check guards against someone resetting our interrupt flag
  137. // in the time between when interrupt_mutex is released in
  138. // _Jv_ThreadInterrupt and the interval of time between the
  139. // WaitForMultipleObjects call we just made and our acquisition
  140. // of interrupt_mutex.
  141. if (rval == (WAIT_OBJECT_0 + 2))
  142. current_obj->interrupt_flag = true;
  143. interrupted = current_obj->interrupt_flag;
  144. LeaveCriticalSection (&current->interrupt_mutex);
  145. EnterCriticalSection(&cv->count_mutex);
  146. cv->blocked_count--;
  147. // If we were unblocked by the second event (the broadcast one)
  148. // and nobody is left, then reset the event.
  149. int last_waiter = (rval == (WAIT_OBJECT_0 + 1)) && (cv->blocked_count == 0);
  150. LeaveCriticalSection(&cv->count_mutex);
  151. if (last_waiter)
  152. ResetEvent (cv->ev[1]);
  153. // Call _Jv_MutexLock repeatedly until the mutex's refcount is the
  154. // same as before we originally released it.
  155. while (curcount < count)
  156. {
  157. _Jv_MutexLock (mu);
  158. ++curcount;
  159. }
  160. return interrupted ? _JV_INTERRUPTED : 0;
  161. }
  162. void
  163. _Jv_CondInit (_Jv_ConditionVariable_t *cv)
  164. {
  165. // we do lazy creation of Events since CreateEvent() is insanely expensive
  166. cv->ev[0] = 0;
  167. InitializeCriticalSection (&cv->count_mutex);
  168. cv->blocked_count = 0;
  169. }
  170. void
  171. _Jv_CondDestroy (_Jv_ConditionVariable_t *cv)
  172. {
  173. if (cv->ev[0] != 0)
  174. {
  175. CloseHandle (cv->ev[0]);
  176. CloseHandle (cv->ev[1]);
  177. cv->ev[0] = 0;
  178. }
  179. DeleteCriticalSection (&cv->count_mutex);
  180. }
  181. int
  182. _Jv_CondNotify (_Jv_ConditionVariable_t *cv, _Jv_Mutex_t *mu)
  183. {
  184. if (mu->owner != GetCurrentThreadId ( ))
  185. return _JV_NOT_OWNER;
  186. EnterCriticalSection (&cv->count_mutex);
  187. ensure_condvar_initialized (cv);
  188. int somebody_is_blocked = cv->blocked_count > 0;
  189. LeaveCriticalSection (&cv->count_mutex);
  190. if (somebody_is_blocked)
  191. SetEvent (cv->ev[0]);
  192. return 0;
  193. }
  194. int
  195. _Jv_CondNotifyAll (_Jv_ConditionVariable_t *cv, _Jv_Mutex_t *mu)
  196. {
  197. if (mu->owner != GetCurrentThreadId ( ))
  198. return _JV_NOT_OWNER;
  199. EnterCriticalSection (&cv->count_mutex);
  200. ensure_condvar_initialized (cv);
  201. int somebody_is_blocked = cv->blocked_count > 0;
  202. LeaveCriticalSection (&cv->count_mutex);
  203. if (somebody_is_blocked)
  204. SetEvent (cv->ev[1]);
  205. return 0;
  206. }
  207. //
  208. // Threads.
  209. //
  210. void
  211. _Jv_InitThreads (void)
  212. {
  213. _Jv_ThreadKey = TlsAlloc();
  214. _Jv_ThreadDataKey = TlsAlloc();
  215. daemon_mutex = CreateMutex (NULL, 0, NULL);
  216. daemon_cond = CreateEvent (NULL, 1, 0, NULL);
  217. non_daemon_count = 0;
  218. }
  219. _Jv_Thread_t *
  220. _Jv_ThreadInitData (java::lang::Thread* obj)
  221. {
  222. _Jv_Thread_t *data = (_Jv_Thread_t*)_Jv_Malloc(sizeof(_Jv_Thread_t));
  223. data->flags = 0;
  224. data->handle = 0;
  225. data->thread_obj = obj;
  226. data->interrupt_event = 0;
  227. InitializeCriticalSection (&data->interrupt_mutex);
  228. return data;
  229. }
  230. void
  231. _Jv_ThreadDestroyData (_Jv_Thread_t *data)
  232. {
  233. DeleteCriticalSection (&data->interrupt_mutex);
  234. if (data->interrupt_event)
  235. CloseHandle(data->interrupt_event);
  236. CloseHandle(data->handle);
  237. _Jv_Free(data);
  238. }
  239. void
  240. _Jv_ThreadSetPriority (_Jv_Thread_t *data, jint prio)
  241. {
  242. int actual = THREAD_PRIORITY_NORMAL;
  243. if (data->flags & FLAG_START)
  244. {
  245. switch (prio)
  246. {
  247. case 10:
  248. actual = THREAD_PRIORITY_TIME_CRITICAL;
  249. break;
  250. case 9:
  251. actual = THREAD_PRIORITY_HIGHEST;
  252. break;
  253. case 8:
  254. case 7:
  255. actual = THREAD_PRIORITY_ABOVE_NORMAL;
  256. break;
  257. case 6:
  258. case 5:
  259. actual = THREAD_PRIORITY_NORMAL;
  260. break;
  261. case 4:
  262. case 3:
  263. actual = THREAD_PRIORITY_BELOW_NORMAL;
  264. break;
  265. case 2:
  266. actual = THREAD_PRIORITY_LOWEST;
  267. break;
  268. case 1:
  269. actual = THREAD_PRIORITY_IDLE;
  270. break;
  271. }
  272. SetThreadPriority(data->handle, actual);
  273. }
  274. }
  275. void
  276. _Jv_ThreadRegister (_Jv_Thread_t *data)
  277. {
  278. TlsSetValue (_Jv_ThreadKey, data->thread_obj);
  279. TlsSetValue (_Jv_ThreadDataKey, data);
  280. }
  281. void
  282. _Jv_ThreadUnRegister ()
  283. {
  284. TlsSetValue (_Jv_ThreadKey, NULL);
  285. TlsSetValue (_Jv_ThreadDataKey, NULL);
  286. }
  287. // This function is called when a thread is started. We don't arrange
  288. // to call the `run' method directly, because this function must
  289. // return a value.
  290. static DWORD WINAPI
  291. really_start (void* x)
  292. {
  293. struct starter *info = (struct starter *) x;
  294. _Jv_ThreadRegister (info->data);
  295. info->method (info->data->thread_obj);
  296. if (! (info->data->flags & FLAG_DAEMON))
  297. {
  298. WaitForSingleObject (daemon_mutex, INFINITE);
  299. non_daemon_count--;
  300. if (! non_daemon_count)
  301. SetEvent (daemon_cond);
  302. ReleaseMutex (daemon_mutex);
  303. }
  304. return 0;
  305. }
  306. void
  307. _Jv_ThreadStart (java::lang::Thread *thread, _Jv_Thread_t *data, _Jv_ThreadStartFunc *meth)
  308. {
  309. DWORD id;
  310. struct starter *info;
  311. // Do nothing if thread has already started
  312. if (data->flags & FLAG_START)
  313. return;
  314. data->flags |= FLAG_START;
  315. info = (struct starter *) _Jv_AllocBytes (sizeof (struct starter));
  316. info->method = meth;
  317. info->data = data;
  318. if (! thread->isDaemon ())
  319. {
  320. WaitForSingleObject (daemon_mutex, INFINITE);
  321. non_daemon_count++;
  322. ReleaseMutex (daemon_mutex);
  323. }
  324. else
  325. data->flags |= FLAG_DAEMON;
  326. data->handle = GC_CreateThread(NULL, 0, really_start, info, 0, &id);
  327. _Jv_ThreadSetPriority(data, thread->getPriority());
  328. }
  329. void
  330. _Jv_ThreadWait (void)
  331. {
  332. WaitForSingleObject (daemon_mutex, INFINITE);
  333. if (non_daemon_count)
  334. {
  335. ReleaseMutex (daemon_mutex);
  336. WaitForSingleObject (daemon_cond, INFINITE);
  337. }
  338. }
  339. //
  340. // Interrupt support
  341. //
  342. HANDLE
  343. _Jv_Win32GetInterruptEvent (void)
  344. {
  345. _Jv_Thread_t *current = _Jv_ThreadCurrentData ();
  346. EnterCriticalSection (&current->interrupt_mutex);
  347. ensure_interrupt_event_initialized (current->interrupt_event);
  348. HANDLE hEvent = current->interrupt_event;
  349. LeaveCriticalSection (&current->interrupt_mutex);
  350. return hEvent;
  351. }
  352. void
  353. _Jv_ThreadInterrupt (_Jv_Thread_t *data)
  354. {
  355. EnterCriticalSection (&data->interrupt_mutex);
  356. ensure_interrupt_event_initialized (data->interrupt_event);
  357. data->thread_obj->interrupt_flag = true;
  358. SetEvent (data->interrupt_event);
  359. LeaveCriticalSection (&data->interrupt_mutex);
  360. }
  361. // park() / unpark() support
  362. void
  363. ParkHelper::init ()
  364. {
  365. // We initialize our critical section, but not our event.
  366. InitializeCriticalSection (&cs);
  367. event = NULL;
  368. }
  369. void
  370. ParkHelper::init_event()
  371. {
  372. EnterCriticalSection (&cs);
  373. if (!event)
  374. {
  375. // Create an auto-reset event.
  376. event = CreateEvent(NULL, 0, 0, NULL);
  377. if (!event) JvFail("CreateEvent() failed");
  378. }
  379. LeaveCriticalSection (&cs);
  380. }
  381. void
  382. ParkHelper::deactivate ()
  383. {
  384. permit = ::java::lang::Thread::THREAD_PARK_DEAD;
  385. }
  386. void
  387. ParkHelper::destroy()
  388. {
  389. if (event) CloseHandle (event);
  390. DeleteCriticalSection (&cs);
  391. }
  392. /**
  393. * Releases the block on a thread created by _Jv_ThreadPark(). This
  394. * method can also be used to terminate a blockage caused by a prior
  395. * call to park. This operation is unsafe, as the thread must be
  396. * guaranteed to be live.
  397. *
  398. * @param thread the thread to unblock.
  399. */
  400. void
  401. ParkHelper::unpark ()
  402. {
  403. using namespace ::java::lang;
  404. LONG volatile* ptr = &permit;
  405. // If this thread is in state RUNNING, give it a permit and return
  406. // immediately.
  407. if (compare_and_exchange
  408. (ptr, Thread::THREAD_PARK_RUNNING, Thread::THREAD_PARK_PERMIT))
  409. return;
  410. // If this thread is parked, put it into state RUNNING and send it a
  411. // signal.
  412. if (compare_and_exchange
  413. (ptr, Thread::THREAD_PARK_PARKED, Thread::THREAD_PARK_RUNNING))
  414. {
  415. init_event ();
  416. SetEvent (event);
  417. }
  418. }
  419. /**
  420. * Blocks the thread until a matching _Jv_ThreadUnpark() occurs, the
  421. * thread is interrupted or the optional timeout expires. If an
  422. * unpark call has already occurred, this also counts. A timeout
  423. * value of zero is defined as no timeout. When isAbsolute is true,
  424. * the timeout is in milliseconds relative to the epoch. Otherwise,
  425. * the value is the number of nanoseconds which must occur before
  426. * timeout. This call may also return spuriously (i.e. for no
  427. * apparent reason).
  428. *
  429. * @param isAbsolute true if the timeout is specified in milliseconds from
  430. * the epoch.
  431. * @param time either the number of nanoseconds to wait, or a time in
  432. * milliseconds from the epoch to wait for.
  433. */
  434. void
  435. ParkHelper::park (jboolean isAbsolute, jlong time)
  436. {
  437. using namespace ::java::lang;
  438. LONG volatile* ptr = &permit;
  439. // If we have a permit, return immediately.
  440. if (compare_and_exchange
  441. (ptr, Thread::THREAD_PARK_PERMIT, Thread::THREAD_PARK_RUNNING))
  442. return;
  443. // Determine the number of milliseconds to wait.
  444. jlong millis = 0, nanos = 0;
  445. if (time)
  446. {
  447. if (isAbsolute)
  448. {
  449. millis = time - ::java::lang::System::currentTimeMillis();
  450. nanos = 0;
  451. }
  452. else
  453. {
  454. millis = 0;
  455. nanos = time;
  456. }
  457. if (nanos)
  458. {
  459. millis += nanos / 1000000;
  460. if (millis == 0)
  461. millis = 1;
  462. // ...otherwise, we'll block indefinitely.
  463. }
  464. }
  465. if (millis < 0) return;
  466. // Can this ever happen?
  467. if (compare_and_exchange
  468. (ptr, Thread::THREAD_PARK_RUNNING, Thread::THREAD_PARK_PARKED))
  469. {
  470. init_event();
  471. DWORD timeout = millis==0 ? INFINITE : (DWORD) millis;
  472. WaitForSingleObject (event, timeout);
  473. // If we were unparked by some other thread, this will already
  474. // be in state THREAD_PARK_RUNNING. If we timed out, we have to
  475. // do it ourself.
  476. compare_and_exchange
  477. (ptr, Thread::THREAD_PARK_PARKED, Thread::THREAD_PARK_RUNNING);
  478. }
  479. }