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/io-layer/io-layer.h>
18 #include <mono/os/gc_wrapper.h>
20 #undef THREAD_LOCK_DEBUG
23 * The monitor implementation here is based on
24 * http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf and
25 * http://www.research.ibm.com/people/d/dfb/papers/Bacon98Thin.ps
27 * The Dice paper describes a technique for saving lock record space
28 * by returning records to a free list when they become unused. That
29 * sounds like unnecessary complexity to me, though if it becomes
30 * clear that unused lock records are taking up lots of space or we
31 * need to shave more time off by avoiding a malloc then we can always
32 * implement the free list idea later. The timeout parameter to
33 * try_enter voids some of the assumptions about the reference count
34 * field in Dice's implementation too. In his version, the thread
35 * attempting to lock a contended object will block until it succeeds,
36 * so the reference count will never be decremented while an object is
39 * Bacon's thin locks have a fast path that doesn't need a lock record
40 * for the common case of locking an unlocked or shallow-nested
41 * object, but the technique relies on encoding the thread ID in 15
42 * bits (to avoid too much per-object space overhead.) Unfortunately
43 * I don't think it's possible to reliably encode a pthread_t into 15
44 * bits. (The JVM implementation used seems to have a 15-bit
45 * per-thread identifier available.)
47 * This implementation then combines Dice's basic lock model with
48 * Bacon's simplification of keeping a lock record for the lifetime of
53 static void mon_finalize (void *o, void *unused)
55 MonoThreadsSync *mon=(MonoThreadsSync *)o;
57 #ifdef THREAD_LOCK_DEBUG
58 g_message (G_GNUC_PRETTY_FUNCTION ": Finalizing sync %p", mon);
61 if(mon->entry_sem!=NULL) {
62 CloseHandle (mon->entry_sem);
64 /* If this isn't empty then something is seriously broken - it
65 * means a thread is still waiting on the object that owned
66 * this lock, but the object has been finalized.
68 g_assert (mon->wait_list==NULL);
71 static MonoThreadsSync *mon_new(guint32 id)
76 new=(MonoThreadsSync *)GC_MALLOC (sizeof(MonoThreadsSync));
77 GC_REGISTER_FINALIZER (new, mon_finalize, NULL, NULL, NULL);
79 /* This should be freed when the object that owns it is
82 new=(MonoThreadsSync *)g_new0 (MonoThreadsSync, 1);
90 gboolean mono_monitor_try_enter (MonoObject *obj, guint32 ms)
93 guint32 id=GetCurrentThreadId ();
95 guint32 then, now, delta;
99 #ifdef THREAD_LOCK_DEBUG
100 g_message(G_GNUC_PRETTY_FUNCTION
101 ": (%d) Trying to lock object %p (%d ms)", id, obj, ms);
105 mon=obj->synchronisation;
107 /* If the object has never been locked... */
110 if(InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, mon, NULL)==NULL) {
111 /* Successfully locked */
114 /* Another thread got in first, so try again.
115 * GC will take care of the monitor record
117 #ifndef HAVE_BOEHM_GC
118 mon_finalize (mon, NULL);
124 /* If the object is currently locked by this thread... */
130 /* If the object has previously been locked but isn't now... */
132 /* This case differs from Dice's case 3 because we don't
133 * deflate locks or cache unused lock records
136 /* Try to install our ID in the owner field, nest
137 * should have been left at 1 by the previous unlock
140 if(InterlockedCompareExchange (&mon->owner, id, 0)==0) {
142 g_assert (mon->nest==1);
150 /* The object must be locked by someone else... */
152 /* If ms is 0 we don't block, but just fail straight away */
154 #ifdef THREAD_LOCK_DEBUG
155 g_message (G_GNUC_PRETTY_FUNCTION
156 ": (%d) timed out, returning FALSE", id);
162 /* The slow path begins here. We need to make sure theres a
163 * semaphore handle (creating it if necessary), and block on
166 if(mon->entry_sem==NULL) {
167 /* Create the semaphore */
168 sem=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
169 if(InterlockedCompareExchangePointer ((gpointer*)&mon->entry_sem, sem, NULL)!=NULL) {
170 /* Someone else just put a handle here */
175 /* If we need to time out, record a timestamp and adjust ms,
176 * because WaitForSingleObject doesn't tell us how long it
179 * Don't block forever here, because theres a chance the owner
180 * thread released the lock while we were creating the
181 * semaphore: we would not get the wakeup. Using the event
182 * handle technique from pulse/wait would involve locking the
183 * lock struct and therefore slowing down the fast path.
186 then=GetTickCount ();
196 InterlockedIncrement (&mon->entry_count);
197 ret=WaitForSingleObject (mon->entry_sem, waitms);
198 InterlockedDecrement (&mon->entry_count);
204 /* The counter must have wrapped around */
205 #ifdef THREAD_LOCK_DEBUG
206 g_message (G_GNUC_PRETTY_FUNCTION
207 ": wrapped around! now=0x%x then=0x%x",
211 now+=(0xffffffff - then);
214 #ifdef THREAD_LOCK_DEBUG
215 g_message (G_GNUC_PRETTY_FUNCTION ": wrap rejig: now=0x%x then=0x%x delta=0x%x", now, then, now-then);
226 if(ret==WAIT_TIMEOUT && ms>0) {
231 if(ret==WAIT_TIMEOUT) {
232 /* Infinite wait, so just try again */
237 if(ret==WAIT_OBJECT_0) {
238 /* retry from the top */
242 /* We must have timed out */
243 #ifdef THREAD_LOCK_DEBUG
244 g_message (G_GNUC_PRETTY_FUNCTION
245 ": (%d) timed out waiting, returning FALSE", id);
251 void mono_monitor_exit (MonoObject *obj)
253 MonoThreadsSync *mon;
256 #ifdef THREAD_LOCK_DEBUG
257 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Unlocking %p",
258 GetCurrentThreadId (), obj);
261 mon=obj->synchronisation;
264 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
267 if(mon->owner!=GetCurrentThreadId ()) {
268 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
274 #ifdef THREAD_LOCK_DEBUG
275 g_message(G_GNUC_PRETTY_FUNCTION
276 ": (%d) Object %p is now unlocked",
277 GetCurrentThreadId (), obj);
280 /* object is now unlocked, leave nest==1 so we don't
281 * need to set it when the lock is reacquired
285 /* Do the wakeup stuff. It's possible that the last
286 * blocking thread gave up waiting just before we
287 * release the semaphore resulting in a futile wakeup
288 * next time there's contention for this object, but
289 * it means we don't have to waste time locking the
292 if(mon->entry_count>0) {
293 ReleaseSemaphore (mon->entry_sem, 1, NULL);
296 #ifdef THREAD_LOCK_DEBUG
297 g_message(G_GNUC_PRETTY_FUNCTION
298 ": (%d) Object %p is now locked %d times",
299 GetCurrentThreadId (), obj,
306 gboolean ves_icall_System_Threading_Monitor_Monitor_try_enter(MonoObject *obj,
311 return(mono_monitor_try_enter (obj, ms));
314 void ves_icall_System_Threading_Monitor_Monitor_exit(MonoObject *obj)
318 return(mono_monitor_exit (obj));
321 gboolean ves_icall_System_Threading_Monitor_Monitor_test_owner(MonoObject *obj)
323 MonoThreadsSync *mon;
327 #ifdef THREAD_LOCK_DEBUG
328 g_message(G_GNUC_PRETTY_FUNCTION
329 ": Testing if %p is owned by thread %d", obj,
330 GetCurrentThreadId());
333 mon=obj->synchronisation;
338 if(mon->owner==GetCurrentThreadId ()) {
345 gboolean ves_icall_System_Threading_Monitor_Monitor_test_synchronised(MonoObject *obj)
347 MonoThreadsSync *mon;
351 #ifdef THREAD_LOCK_DEBUG
352 g_message(G_GNUC_PRETTY_FUNCTION
353 ": (%d) Testing if %p is owned by any thread",
354 GetCurrentThreadId (), obj);
357 mon=obj->synchronisation;
369 /* All wait list manipulation in the pulse, pulseall and wait
370 * functions happens while the monitor lock is held, so we don't need
371 * any extra struct locking
374 void ves_icall_System_Threading_Monitor_Monitor_pulse(MonoObject *obj)
376 MonoThreadsSync *mon;
380 #ifdef THREAD_LOCK_DEBUG
381 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Pulsing %p",
382 GetCurrentThreadId (), obj);
385 mon=obj->synchronisation;
387 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
390 if(mon->owner!=GetCurrentThreadId ()) {
391 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
395 #ifdef THREAD_LOCK_DEBUG
396 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) %d threads waiting",
397 GetCurrentThreadId (), g_slist_length (mon->wait_list));
400 if(mon->wait_list!=NULL) {
401 #ifdef THREAD_LOCK_DEBUG
402 g_message(G_GNUC_PRETTY_FUNCTION
403 ": (%d) signalling and dequeuing handle %p",
404 GetCurrentThreadId (), mon->wait_list->data);
407 SetEvent (mon->wait_list->data);
408 mon->wait_list=g_slist_remove (mon->wait_list,
409 mon->wait_list->data);
413 void ves_icall_System_Threading_Monitor_Monitor_pulse_all(MonoObject *obj)
415 MonoThreadsSync *mon;
419 #ifdef THREAD_LOCK_DEBUG
420 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Pulsing all %p",
421 GetCurrentThreadId (), obj);
424 mon=obj->synchronisation;
426 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
429 if(mon->owner!=GetCurrentThreadId ()) {
430 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
434 #ifdef THREAD_LOCK_DEBUG
435 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) %d threads waiting",
436 GetCurrentThreadId (), g_slist_length (mon->wait_list));
439 while(mon->wait_list!=NULL) {
440 #ifdef THREAD_LOCK_DEBUG
441 g_message(G_GNUC_PRETTY_FUNCTION
442 ": (%d) signalling and dequeuing handle %p",
443 GetCurrentThreadId (), mon->wait_list->data);
446 SetEvent (mon->wait_list->data);
447 mon->wait_list=g_slist_remove (mon->wait_list,
448 mon->wait_list->data);
452 gboolean ves_icall_System_Threading_Monitor_Monitor_wait(MonoObject *obj,
455 MonoThreadsSync *mon;
459 gboolean success=FALSE, regain;
463 #ifdef THREAD_LOCK_DEBUG
464 g_message(G_GNUC_PRETTY_FUNCTION
465 ": (%d) Trying to wait for %p with timeout %dms",
466 GetCurrentThreadId (), obj, ms);
469 mon=obj->synchronisation;
471 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
474 if(mon->owner!=GetCurrentThreadId ()) {
475 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
479 event=CreateEvent (NULL, FALSE, FALSE, NULL);
481 mono_raise_exception (mono_get_exception_synchronization_lock ("Failed to set up wait event"));
485 #ifdef THREAD_LOCK_DEBUG
486 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) queuing handle %p",
487 GetCurrentThreadId (), event);
490 mon->wait_list=g_slist_append (mon->wait_list, event);
492 /* Save the nest count, and release the lock */
495 mono_monitor_exit (obj);
497 #ifdef THREAD_LOCK_DEBUG
498 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Unlocked %p lock %p",
499 GetCurrentThreadId (), obj, mon);
502 /* There's no race between unlocking mon and waiting for the
503 * event, because auto reset events are sticky, and this event
504 * is private to this thread. Therefore even if the event was
505 * signalled before we wait, we still succeed.
507 ret=WaitForSingleObject (event, ms);
509 /* Regain the lock with the previous nest count */
510 regain=mono_monitor_try_enter (obj, INFINITE);
512 /* Something went wrong, so throw a
513 * SynchronizationLockException
516 mono_raise_exception (mono_get_exception_synchronization_lock ("Failed to regain lock"));
522 #ifdef THREAD_LOCK_DEBUG
523 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Regained %p lock %p",
524 GetCurrentThreadId (), obj, mon);
527 if(ret==WAIT_TIMEOUT) {
528 /* Poll the event again, just in case it was signalled
529 * while we were trying to regain the monitor lock
531 ret=WaitForSingleObject (event, 0);
534 /* Pulse will have popped our event from the queue if it signalled
535 * us, so we only do it here if the wait timed out.
537 * This avoids a race condition where the thread holding the
538 * lock can Pulse several times before the WaitForSingleObject
539 * returns. If we popped the queue here then this event might
540 * be signalled more than once, thereby starving another
544 if(ret==WAIT_OBJECT_0) {
545 #ifdef THREAD_LOCK_DEBUG
546 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Success",
547 GetCurrentThreadId ());
551 #ifdef THREAD_LOCK_DEBUG
552 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
553 GetCurrentThreadId ());
554 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) dequeuing handle %p",
555 GetCurrentThreadId (), event);
557 /* No pulse, so we have to remove ourself from the
560 mon->wait_list=g_slist_remove (mon->wait_list, event);