2 * monitor.c: Monitor locking functions
5 * Dick Porter (dick@ximian.com)
7 * (C) 2003 Ximian, Inc.
13 #include <mono/metadata/monitor.h>
14 #include <mono/metadata/threads-types.h>
15 #include <mono/metadata/exception.h>
16 #include <mono/metadata/threads.h>
17 #include <mono/io-layer/io-layer.h>
18 #include <mono/metadata/object-internals.h>
20 #include <mono/os/gc_wrapper.h>
22 /*#define LOCK_DEBUG(a) do { a; } while (0)*/
26 * The monitor implementation here is based on
27 * http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf and
28 * http://www.research.ibm.com/people/d/dfb/papers/Bacon98Thin.ps
30 * The Dice paper describes a technique for saving lock record space
31 * by returning records to a free list when they become unused. That
32 * sounds like unnecessary complexity to me, though if it becomes
33 * clear that unused lock records are taking up lots of space or we
34 * need to shave more time off by avoiding a malloc then we can always
35 * implement the free list idea later. The timeout parameter to
36 * try_enter voids some of the assumptions about the reference count
37 * field in Dice's implementation too. In his version, the thread
38 * attempting to lock a contended object will block until it succeeds,
39 * so the reference count will never be decremented while an object is
42 * Bacon's thin locks have a fast path that doesn't need a lock record
43 * for the common case of locking an unlocked or shallow-nested
44 * object, but the technique relies on encoding the thread ID in 15
45 * bits (to avoid too much per-object space overhead.) Unfortunately
46 * I don't think it's possible to reliably encode a pthread_t into 15
47 * bits. (The JVM implementation used seems to have a 15-bit
48 * per-thread identifier available.)
50 * This implementation then combines Dice's basic lock model with
51 * Bacon's simplification of keeping a lock record for the lifetime of
57 mon_finalize (void *o, void *unused)
59 MonoThreadsSync *mon = o;
61 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Finalizing sync %p", mon));
63 if (mon->entry_sem != NULL) {
64 CloseHandle (mon->entry_sem);
66 /* If this isn't empty then something is seriously broken - it
67 * means a thread is still waiting on the object that owned
68 * this lock, but the object has been finalized.
70 g_assert (mon->wait_list == NULL);
73 static MonoThreadsSync *
79 new = GC_MALLOC (sizeof (MonoThreadsSync));
80 GC_REGISTER_FINALIZER (new, mon_finalize, NULL, NULL, NULL);
82 /* This should be freed when the object that owns it is
85 new = g_new0 (MonoThreadsSync, 1);
93 /* If allow_interruption==TRUE, the method will be interrumped if abort or suspend
94 * is requested. In this case it returns -1.
97 mono_monitor_try_enter_internal (MonoObject *obj, guint32 ms, gboolean allow_interruption)
100 guint32 id = GetCurrentThreadId ();
102 guint32 then = 0, now, delta;
106 LOCK_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
107 ": (%d) Trying to lock object %p (%d ms)", id, obj, ms));
110 mon = obj->synchronisation;
112 /* If the object has never been locked... */
115 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, mon, NULL) == NULL) {
116 /* Successfully locked */
119 /* Another thread got in first, so try again.
120 * GC will take care of the monitor record
122 #ifndef HAVE_BOEHM_GC
123 mon_finalize (mon, NULL);
129 /* If the object is currently locked by this thread... */
130 if (mon->owner == id) {
135 /* If the object has previously been locked but isn't now... */
137 /* This case differs from Dice's case 3 because we don't
138 * deflate locks or cache unused lock records
140 if (mon->owner == 0) {
141 /* Try to install our ID in the owner field, nest
142 * should have been left at 1 by the previous unlock
145 if (InterlockedCompareExchange (&mon->owner, id, 0) == 0) {
147 g_assert (mon->nest == 1);
155 /* The object must be locked by someone else... */
157 /* If ms is 0 we don't block, but just fail straight away */
159 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) timed out, returning FALSE", id));
163 /* The slow path begins here. We need to make sure theres a
164 * semaphore handle (creating it if necessary), and block on
167 if (mon->entry_sem == NULL) {
168 /* Create the semaphore */
169 sem = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
170 if (InterlockedCompareExchangePointer ((gpointer*)&mon->entry_sem, sem, NULL) != NULL) {
171 /* Someone else just put a handle here */
176 /* If we need to time out, record a timestamp and adjust ms,
177 * because WaitForSingleObject doesn't tell us how long it
180 * Don't block forever here, because theres a chance the owner
181 * thread released the lock while we were creating the
182 * semaphore: we would not get the wakeup. Using the event
183 * handle technique from pulse/wait would involve locking the
184 * lock struct and therefore slowing down the fast path.
186 if (ms != INFINITE) {
187 then = GetTickCount ();
197 InterlockedIncrement (&mon->entry_count);
198 ret = WaitForSingleObjectEx (mon->entry_sem, waitms, allow_interruption);
199 InterlockedDecrement (&mon->entry_count);
201 if (ms != INFINITE) {
202 now = GetTickCount ();
205 /* The counter must have wrapped around */
206 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
207 ": wrapped around! now=0x%x then=0x%x", now, then));
209 now += (0xffffffff - then);
212 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": wrap rejig: now=0x%x then=0x%x delta=0x%x", now, then, now-then));
222 if ((ret == WAIT_TIMEOUT || (ret == WAIT_IO_COMPLETION && !allow_interruption)) && ms > 0) {
227 if (ret == WAIT_TIMEOUT || (ret == WAIT_IO_COMPLETION && !allow_interruption)) {
228 /* Infinite wait, so just try again */
233 if (ret == WAIT_OBJECT_0) {
234 /* retry from the top */
238 /* We must have timed out */
239 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) timed out waiting, returning FALSE", id));
241 if (ret == WAIT_IO_COMPLETION)
248 mono_monitor_enter (MonoObject *obj)
250 return mono_monitor_try_enter_internal (obj, INFINITE, FALSE) == 1;
254 mono_monitor_try_enter (MonoObject *obj, guint32 ms)
256 return mono_monitor_try_enter_internal (obj, ms, FALSE) == 1;
260 mono_monitor_exit (MonoObject *obj)
262 MonoThreadsSync *mon;
265 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Unlocking %p", GetCurrentThreadId (), obj));
267 mon = obj->synchronisation;
270 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
273 if (mon->owner != GetCurrentThreadId ()) {
277 nest = mon->nest - 1;
279 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
280 ": (%d) Object %p is now unlocked", GetCurrentThreadId (), obj));
282 /* object is now unlocked, leave nest==1 so we don't
283 * need to set it when the lock is reacquired
287 /* Do the wakeup stuff. It's possible that the last
288 * blocking thread gave up waiting just before we
289 * release the semaphore resulting in a futile wakeup
290 * next time there's contention for this object, but
291 * it means we don't have to waste time locking the
294 if (mon->entry_count > 0) {
295 ReleaseSemaphore (mon->entry_sem, 1, NULL);
298 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
299 ": (%d) Object %p is now locked %d times", GetCurrentThreadId (), obj, nest));
305 ves_icall_System_Threading_Monitor_Monitor_try_enter (MonoObject *obj, guint32 ms)
310 res = mono_monitor_try_enter_internal (obj, ms, TRUE);
312 mono_thread_interruption_checkpoint ();
319 ves_icall_System_Threading_Monitor_Monitor_exit (MonoObject *obj)
321 mono_monitor_exit (obj);
325 ves_icall_System_Threading_Monitor_Monitor_test_owner (MonoObject *obj)
327 MonoThreadsSync *mon;
329 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
330 ": Testing if %p is owned by thread %d", obj, GetCurrentThreadId()));
332 mon = obj->synchronisation;
337 if(mon->owner==GetCurrentThreadId ()) {
345 ves_icall_System_Threading_Monitor_Monitor_test_synchronised (MonoObject *obj)
347 MonoThreadsSync *mon;
349 LOCK_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
350 ": (%d) Testing if %p is owned by any thread", GetCurrentThreadId (), obj));
352 mon = obj->synchronisation;
357 if (mon->owner != 0) {
364 /* All wait list manipulation in the pulse, pulseall and wait
365 * functions happens while the monitor lock is held, so we don't need
366 * any extra struct locking
370 ves_icall_System_Threading_Monitor_Monitor_pulse (MonoObject *obj)
372 MonoThreadsSync *mon;
374 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Pulsing %p",
375 GetCurrentThreadId (), obj));
377 mon = obj->synchronisation;
379 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
382 if (mon->owner != GetCurrentThreadId ()) {
383 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
387 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) %d threads waiting",
388 GetCurrentThreadId (), g_slist_length (mon->wait_list)));
390 if (mon->wait_list != NULL) {
391 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
392 ": (%d) signalling and dequeuing handle %p",
393 GetCurrentThreadId (), mon->wait_list->data));
395 SetEvent (mon->wait_list->data);
396 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
401 ves_icall_System_Threading_Monitor_Monitor_pulse_all (MonoObject *obj)
403 MonoThreadsSync *mon;
405 LOCK_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Pulsing all %p",
406 GetCurrentThreadId (), obj));
408 mon = obj->synchronisation;
410 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
413 if (mon->owner != GetCurrentThreadId ()) {
414 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
418 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) %d threads waiting",
419 GetCurrentThreadId (), g_slist_length (mon->wait_list)));
421 while (mon->wait_list != NULL) {
422 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
423 ": (%d) signalling and dequeuing handle %p",
424 GetCurrentThreadId (), mon->wait_list->data));
426 SetEvent (mon->wait_list->data);
427 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
432 ves_icall_System_Threading_Monitor_Monitor_wait (MonoObject *obj, guint32 ms)
434 MonoThreadsSync *mon;
438 gboolean success = FALSE;
440 MonoThread *thread = mono_thread_current ();
442 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
443 ": (%d) Trying to wait for %p with timeout %dms",
444 GetCurrentThreadId (), obj, ms));
446 mon = obj->synchronisation;
448 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
451 if (mon->owner != GetCurrentThreadId ()) {
452 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
456 event = CreateEvent (NULL, FALSE, FALSE, NULL);
458 mono_raise_exception (mono_get_exception_synchronization_lock ("Failed to set up wait event"));
462 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) queuing handle %p",
463 GetCurrentThreadId (), event));
465 mono_monitor_enter (thread->synch_lock);
466 thread->state |= ThreadState_WaitSleepJoin;
467 mono_monitor_exit (thread->synch_lock);
469 mon->wait_list = g_slist_append (mon->wait_list, event);
471 /* Save the nest count, and release the lock */
474 mono_monitor_exit (obj);
476 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Unlocked %p lock %p",
477 GetCurrentThreadId (), obj, mon));
479 /* There's no race between unlocking mon and waiting for the
480 * event, because auto reset events are sticky, and this event
481 * is private to this thread. Therefore even if the event was
482 * signalled before we wait, we still succeed.
484 ret = WaitForSingleObjectEx (event, ms, TRUE);
486 /* Reset the thread state fairly early, so we don't have to worry
487 * about the monitor error checking
489 mono_monitor_enter (thread->synch_lock);
490 thread->state &= ~ThreadState_WaitSleepJoin;
491 mono_monitor_exit (thread->synch_lock);
493 if (mono_thread_interruption_requested ()) {
498 /* Regain the lock with the previous nest count */
500 regain = mono_monitor_try_enter_internal (obj, INFINITE, TRUE);
502 mono_thread_interruption_checkpoint ();
503 } while (regain == -1);
506 /* Something went wrong, so throw a
507 * SynchronizationLockException
510 mono_raise_exception (mono_get_exception_synchronization_lock ("Failed to regain lock"));
516 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Regained %p lock %p",
517 GetCurrentThreadId (), obj, mon));
519 if (ret == WAIT_TIMEOUT) {
520 /* Poll the event again, just in case it was signalled
521 * while we were trying to regain the monitor lock
523 ret = WaitForSingleObjectEx (event, 0, FALSE);
526 /* Pulse will have popped our event from the queue if it signalled
527 * us, so we only do it here if the wait timed out.
529 * This avoids a race condition where the thread holding the
530 * lock can Pulse several times before the WaitForSingleObject
531 * returns. If we popped the queue here then this event might
532 * be signalled more than once, thereby starving another
536 if (ret == WAIT_OBJECT_0) {
537 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Success",
538 GetCurrentThreadId ()));
541 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed, dequeuing handle %p",
542 GetCurrentThreadId (), event));
543 /* No pulse, so we have to remove ourself from the
546 mon->wait_list = g_slist_remove (mon->wait_list, event);