Monitor.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. #include "il2cpp-config.h"
  2. #include "il2cpp-object-internals.h"
  3. #include "vm/Monitor.h"
  4. #if IL2CPP_SUPPORT_THREADS
  5. #include "os/Atomic.h"
  6. #include "os/Event.h"
  7. #include "os/Semaphore.h"
  8. #include "os/Thread.h"
  9. #include "vm/Exception.h"
  10. #include "vm/Thread.h"
  11. #include "utils/ThreadSafeFreeList.h"
  12. #include <limits>
  13. #include <exception>
  14. #include "Baselib.h"
  15. #include "Cpp/Atomic.h"
  16. // Mostly follows the algorithm outlined in "Implementing Fast Java Monitors with Relaxed-Locks".
  17. /// State of a lock associated with an object.
  18. ///
  19. /// Allocated from the normal non-GC heap and kept on a free list. This means that an object that is
  20. /// not unlocked before it is reclaimed will leak its monitor. However, it allows us to not have to
  21. /// synchronize with the GC and to efficiently reuse a small number of monitor instances between an
  22. /// arbitrary number of managed objects.
  23. ///
  24. // NOTE: We do *NOT* allow deletion of monitors as threads may be hanging on to monitors even as they
  25. // are already back on the free list (and maybe even in use somewhere else already).
  26. struct MonitorData : public il2cpp::utils::ThreadSafeFreeListNode
  27. {
  28. static const il2cpp::os::Thread::ThreadId kCanBeAcquiredByOtherThread = il2cpp::os::Thread::kInvalidThreadId;
  29. static const il2cpp::os::Thread::ThreadId kHasBeenReturnedToFreeList = (il2cpp::os::Thread::ThreadId)-1;
  30. /// ID of thread that currently has the object locked or one of the two values above.
  31. ///
  32. /// This signals three possible states:
  33. ///
  34. /// 1) Contains a valid thread ID. Means the monitor is owned by that thread and only that thread can
  35. /// change the value of this field.
  36. /// 2) Contains kCanBeAcquiredByOtherThread. Means monitor is still live and attached to an object
  37. /// but is up for grabs by whichever thread manages to swap the value of this field for its own
  38. /// thread ID first.
  39. /// 3) Contains kHasBeenReturnedToFreeList. Means monitor is not attached to any object and can be
  40. /// acquired by any thread *but* only through the free list.
  41. baselib::atomic<il2cpp::os::Thread::ThreadId> owningThreadId;
  42. baselib::atomic<bool> threadAborted;
  43. /// Number of times the object has been locked on the owning thread. Everything above 1 indicates
  44. /// a recursive lock.
  45. /// NOTE: This field is never reset to zero.
  46. uint32_t recursiveLockingCount;
  47. /// Semaphore used to signal other blocked threads that the monitor has become available.
  48. /// The "ready queue" is implicit in the list of threads waiting on this semaphore.
  49. il2cpp::os::Semaphore semaphore;
  50. /// Number of threads that are already waiting or are about to wait for a lock on the monitor.
  51. baselib::atomic<uint32_t> numThreadsWaitingForSemaphore;
  52. /// Event that a waiting thread fires to acknowledge that it has been kicked off a monitor by the thread
  53. /// already holding a lock on the object being waited for. This happens when the locking thread decides
  54. /// to deflate the locked object and thus kill the monitor but then some other thread comes along and
  55. /// decides to wait on the monitor-to-be-killed.
  56. il2cpp::os::Event flushAcknowledged;
  57. /// Node in list of waiting threads.
  58. ///
  59. /// Memory management is done the same way as for MonitorData itself. The same constraints apply.
  60. /// Wait nodes are returned to the free list by the threads that have created them except for abandoned
  61. /// nodes which may be returned by the pulsing thread.
  62. ///
  63. /// NOTE: Every wait node must be cleaned up by the wait thread that allocated it.
  64. struct PulseWaitingListNode : public il2cpp::utils::ThreadSafeFreeListNode
  65. {
  66. enum State
  67. {
  68. /// Node is waiting to be reused.
  69. kUnused,
  70. /// Node is waiting to be signaled.
  71. kWaiting
  72. };
  73. /// Next node in "threadsWaitingForPulse" list.
  74. /// NOTE: Once on the list, this field may only be modified by the thread holding a lock
  75. /// on the respective monitor.
  76. PulseWaitingListNode* nextNode;
  77. /// Event to notify waiting thread of pulse.
  78. il2cpp::os::Event signalWaitingThread;
  79. /// Current usage state. This is not set atomically. Change this state only if you
  80. /// are at a known sequence point.
  81. int32_t state;
  82. static il2cpp::utils::ThreadSafeFreeList<PulseWaitingListNode> s_FreeList;
  83. PulseWaitingListNode()
  84. : nextNode(NULL)
  85. , state(kUnused) {}
  86. void Release()
  87. {
  88. state = kUnused;
  89. signalWaitingThread.Reset();
  90. s_FreeList.Release(this);
  91. }
  92. static PulseWaitingListNode* Allocate()
  93. {
  94. PulseWaitingListNode* node = s_FreeList.Allocate();
  95. IL2CPP_ASSERT(node->state == kUnused);
  96. return node;
  97. }
  98. };
  99. /// List of threads waiting for a pulse on the monitor.
  100. /// NOTE: This field may be modified concurrently by several threads (no lock).
  101. PulseWaitingListNode* threadsWaitingForPulse;
  102. static il2cpp::utils::ThreadSafeFreeList<MonitorData> s_FreeList;
  103. MonitorData()
  104. : owningThreadId(kHasBeenReturnedToFreeList)
  105. , threadAborted(false)
  106. , recursiveLockingCount(1)
  107. , numThreadsWaitingForSemaphore(0)
  108. , threadsWaitingForPulse(NULL)
  109. , semaphore(0, std::numeric_limits<int32_t>::max())
  110. {
  111. }
  112. bool IsAcquired() const
  113. {
  114. return (owningThreadId != kCanBeAcquiredByOtherThread && owningThreadId != kHasBeenReturnedToFreeList);
  115. }
  116. bool IsOwnedByThread(il2cpp::os::Thread::ThreadId threadId) const
  117. {
  118. return owningThreadId == threadId;
  119. }
  120. bool TryAcquire(size_t threadId)
  121. {
  122. // The compare_exchange_strong method can change its first argument.
  123. // We don't care about the changed valuem, though, so ignore it.
  124. il2cpp::os::Thread::ThreadId local = kCanBeAcquiredByOtherThread;
  125. return owningThreadId.compare_exchange_strong(local, threadId);
  126. }
  127. void Unacquire()
  128. {
  129. IL2CPP_ASSERT(owningThreadId == il2cpp::os::Thread::CurrentThreadId());
  130. owningThreadId = kCanBeAcquiredByOtherThread;
  131. }
  132. /// Mark current thread as being blocked in Monitor.Enter(), i.e. as "ready to acquire monitor
  133. /// whenever it becomes available."
  134. void AddCurrentThreadToReadyList()
  135. {
  136. numThreadsWaitingForSemaphore++;
  137. il2cpp::vm::Thread::SetState(il2cpp::vm::Thread::Current(), il2cpp::vm::kThreadStateWaitSleepJoin);
  138. }
  139. /// Mark current thread is no longer being blocked on the monitor.
  140. int RemoveCurrentThreadFromReadyList()
  141. {
  142. int numRemainingWaitingThreads = --numThreadsWaitingForSemaphore;
  143. il2cpp::vm::Thread::ClrState(il2cpp::vm::Thread::Current(), il2cpp::vm::kThreadStateWaitSleepJoin);
  144. return numRemainingWaitingThreads;
  145. }
  146. /// Acknowledge that the owning thread has decided to kill the monitor (a.k.a. deflate the corresponding
  147. /// object) while we were waiting on it.
  148. void VacateDyingMonitor()
  149. {
  150. RemoveCurrentThreadFromReadyList();
  151. flushAcknowledged.Set();
  152. }
  153. void PushOntoPulseWaitingList(PulseWaitingListNode* node)
  154. {
  155. // Change state to waiting. Safe to not do this atomically as at this point,
  156. // the waiting thread is the only one with access to the node.
  157. node->state = PulseWaitingListNode::kWaiting;
  158. // Race other wait threads until we've successfully linked the
  159. // node into the list.
  160. while (true)
  161. {
  162. PulseWaitingListNode* nextNode = threadsWaitingForPulse;
  163. node->nextNode = nextNode;
  164. if (il2cpp::os::Atomic::CompareExchangePointer(&threadsWaitingForPulse, node, nextNode) == nextNode)
  165. break;
  166. }
  167. }
  168. /// Get the next wait node and remove it from the list.
  169. /// NOTE: Calling thread *must* have the monitor locked.
  170. PulseWaitingListNode* PopNextFromPulseWaitingList()
  171. {
  172. IL2CPP_ASSERT(owningThreadId == il2cpp::os::Thread::CurrentThreadId());
  173. PulseWaitingListNode* head = threadsWaitingForPulse;
  174. if (!head)
  175. return NULL;
  176. // Grab the node for ourselves. We take the node even if some other thread
  177. // changes "threadsWaitingForPulse" in the meantime. If that happens, we don't
  178. // unlink the node and the node will stay on the list until the waiting thread
  179. // cleans up the list.
  180. PulseWaitingListNode* next = head->nextNode;
  181. if (il2cpp::os::Atomic::CompareExchangePointer(&threadsWaitingForPulse, next, head) == head)
  182. head->nextNode = NULL;
  183. return head;
  184. }
  185. /// Remove the given waiting node from "threadsWaitingForPulse".
  186. /// NOTE: Calling thread *must* have the monitor locked.
  187. bool RemoveFromPulseWaitingList(PulseWaitingListNode* node)
  188. {
  189. IL2CPP_ASSERT(owningThreadId == il2cpp::os::Thread::CurrentThreadId());
  190. // This function works only because threads calling Wait() on the monitor will only
  191. // ever *prepend* nodes to the list. This means that only the "threadsWaitingForPulse"
  192. // variable is actually shared between threads whereas the list contents are owned
  193. // by the thread that has the monitor locked.
  194. tryAgain:
  195. PulseWaitingListNode * previous = NULL;
  196. for (PulseWaitingListNode* current = threadsWaitingForPulse; current != NULL;)
  197. {
  198. // Go through list looking for node.
  199. if (current != node)
  200. {
  201. previous = current;
  202. current = current->nextNode;
  203. continue;
  204. }
  205. // Node found. Remove.
  206. if (previous)
  207. previous->nextNode = node->nextNode;
  208. else
  209. {
  210. // We may have to change "threadsWaitingForPulse" and thus have to synchronize
  211. // with other threads.
  212. if (il2cpp::os::Atomic::CompareExchangePointer(&threadsWaitingForPulse, node->nextNode, node) != node)
  213. {
  214. // One or more other threads have changed the list.
  215. goto tryAgain;
  216. }
  217. }
  218. node->nextNode = NULL;
  219. return true;
  220. }
  221. // Not found in list.
  222. return false;
  223. }
  224. };
  225. il2cpp::utils::ThreadSafeFreeList<MonitorData> MonitorData::s_FreeList;
  226. il2cpp::utils::ThreadSafeFreeList<MonitorData::PulseWaitingListNode> MonitorData::PulseWaitingListNode::s_FreeList;
  227. static MonitorData* GetMonitorAndThrowIfNotLockedByCurrentThread(Il2CppObject* obj)
  228. {
  229. // Fetch monitor data.
  230. MonitorData* monitor = il2cpp::os::Atomic::ReadPointer(&obj->monitor);
  231. if (!monitor)
  232. {
  233. // No one locked this object.
  234. il2cpp::vm::Exception::Raise(il2cpp::vm::Exception::GetSynchronizationLockException("Object is not locked."));
  235. }
  236. // Throw SynchronizationLockException if we're not holding a lock.
  237. // NOTE: Unlike .NET, Mono simply ignores this and does not throw.
  238. uint64_t currentThreadId = il2cpp::os::Thread::CurrentThreadId();
  239. if (monitor->owningThreadId != currentThreadId && !monitor->threadAborted)
  240. {
  241. il2cpp::vm::Exception::Raise(il2cpp::vm::Exception::GetSynchronizationLockException
  242. ("Object has not been locked by this thread."));
  243. }
  244. return monitor;
  245. }
  246. namespace il2cpp
  247. {
  248. namespace vm
  249. {
  250. void Monitor::Enter(Il2CppObject* object)
  251. {
  252. TryEnter(object, std::numeric_limits<uint32_t>::max());
  253. }
  254. bool Monitor::TryEnter(Il2CppObject* obj, uint32_t timeOutMilliseconds)
  255. {
  256. size_t currentThreadId = il2cpp::os::Thread::CurrentThreadId();
  257. while (true)
  258. {
  259. MonitorData* installedMonitor = il2cpp::os::Atomic::ReadPointer(&obj->monitor);
  260. if (!installedMonitor)
  261. {
  262. // Set up a new monitor.
  263. MonitorData* newlyAllocatedMonitorForThisThread = MonitorData::s_FreeList.Allocate();
  264. il2cpp::os::Thread::ThreadId previousOwnerThreadId = newlyAllocatedMonitorForThisThread->owningThreadId.exchange(currentThreadId);
  265. IL2CPP_ASSERT(previousOwnerThreadId == MonitorData::kHasBeenReturnedToFreeList && "Monitor on freelist cannot be owned by thread!");
  266. // Try to install the monitor on the object (aka "inflate" the object).
  267. if (il2cpp::os::Atomic::CompareExchangePointer(&obj->monitor, newlyAllocatedMonitorForThisThread, (MonitorData*)NULL) == NULL)
  268. {
  269. // Done. There was no contention on this object. This is
  270. // the fast path.
  271. IL2CPP_ASSERT(obj->monitor);
  272. IL2CPP_ASSERT(obj->monitor->recursiveLockingCount == 1);
  273. IL2CPP_ASSERT(obj->monitor->owningThreadId == currentThreadId);
  274. return true;
  275. }
  276. else
  277. {
  278. // Some other thread raced us and won. Retry.
  279. newlyAllocatedMonitorForThisThread->owningThreadId = MonitorData::kHasBeenReturnedToFreeList;
  280. MonitorData::s_FreeList.Release(newlyAllocatedMonitorForThisThread);
  281. continue;
  282. }
  283. }
  284. // Object was locked previously. See if we already have the lock.
  285. if (installedMonitor->owningThreadId == currentThreadId)
  286. {
  287. // Yes, recursive lock. Just increase count.
  288. ++installedMonitor->recursiveLockingCount;
  289. return true;
  290. }
  291. // Attempt to acquire lock if it's free
  292. if (installedMonitor->TryAcquire(currentThreadId))
  293. {
  294. // There is no locking around the sections of this logic to speed
  295. // things up, there is potential for race condition to reset the objects
  296. // monitor. If it has been reset prior to successfully coming out of
  297. // TryAquire, dont return, unaquire the installedMonitor, go back through the logic again to grab a
  298. // a valid monitor.
  299. if (il2cpp::os::Atomic::ReadPointer(&obj->monitor) != installedMonitor)
  300. {
  301. installedMonitor->Unacquire();
  302. continue;
  303. }
  304. // Ownership of monitor passed from previously locking thread to us.
  305. IL2CPP_ASSERT(installedMonitor->recursiveLockingCount == 1);
  306. IL2CPP_ASSERT(obj->monitor == installedMonitor);
  307. return true;
  308. }
  309. // Getting an immediate lock failed, so if we have a zero timeout now,
  310. // entering the monitor failed.
  311. if (timeOutMilliseconds == 0)
  312. return false;
  313. // Object was locked by other thread. Let the monitor know we are waiting for a lock.
  314. installedMonitor->AddCurrentThreadToReadyList();
  315. if (il2cpp::os::Atomic::ReadPointer(&obj->monitor) != installedMonitor)
  316. {
  317. // Another thread deflated the object while we tried to lock it. Get off
  318. // the monitor.
  319. // NOTE: By now we may already be dealing with a monitor that is back on the free list
  320. // or even installed on an object again.
  321. installedMonitor->VacateDyingMonitor();
  322. // NOTE: The "Implementing Fast Java Monitors with Relaxed-Locks" paper describes a path
  323. // that may lead to monitors being leaked if the thread currently holding a lock sees our
  324. // temporary increment of numWaitingThreads and ends up not deflating the object. However,
  325. // we can only ever end up inside this branch here if the locking thread has already decided to
  326. // deflate, so I don't see how we can leak here.
  327. // Retry.
  328. continue;
  329. }
  330. // NOTE: At this point, we are in the waiting line for the monitor. However, the thread currently
  331. // locking the monitor may still have already made the decision to deflate the object so we may
  332. // still get kicked off the monitor.
  333. // Wait for the locking thread to signal us.
  334. while (il2cpp::os::Atomic::ReadPointer(&obj->monitor) == installedMonitor)
  335. {
  336. // Try to grab the object for ourselves.
  337. if (installedMonitor->TryAcquire(currentThreadId))
  338. {
  339. // Ownership of monitor passed from previously locking thread to us.
  340. IL2CPP_ASSERT(installedMonitor->recursiveLockingCount == 1);
  341. IL2CPP_ASSERT(obj->monitor == installedMonitor);
  342. installedMonitor->RemoveCurrentThreadFromReadyList();
  343. return true;
  344. }
  345. // Wait for owner to signal us.
  346. il2cpp::os::WaitStatus waitStatus;
  347. try
  348. {
  349. if (timeOutMilliseconds != std::numeric_limits<uint32_t>::max())
  350. {
  351. // Perform a timed wait.
  352. waitStatus = installedMonitor->semaphore.Wait(timeOutMilliseconds, true);
  353. }
  354. else
  355. {
  356. // Perform an infinite wait. We may still be interrupted, however.
  357. waitStatus = installedMonitor->semaphore.Wait(true);
  358. }
  359. }
  360. catch (Thread::NativeThreadAbortException&)
  361. {
  362. // This signals that the monitor was not entered properly by this thread. Therefore
  363. // a later call to Exit on this monitor should not actually try to exit the monitor,
  364. // because it is not owned by this thread.
  365. installedMonitor->threadAborted = true;
  366. throw;
  367. }
  368. catch (...)
  369. {
  370. // A user APC could throw an exception from within Wait(). This can commonly happen
  371. // during shutdown, when vm::Thread::AbortAllThreads() causes an APC that throws a
  372. // NativeThreadAbortException. Just make sure we clean up properly.
  373. installedMonitor->RemoveCurrentThreadFromReadyList();
  374. throw;
  375. }
  376. ////TODO: adjust wait time if we have a Wait() failure and before going another round
  377. if (waitStatus == kWaitStatusTimeout)
  378. {
  379. // Wait failed. Get us off the list.
  380. int newNumWaitingThreads = installedMonitor->RemoveCurrentThreadFromReadyList();
  381. // If there are no more waiting threads on this monitor, we need to check for leaking.
  382. // This may happen if the locking thread has just been executing a Monitor.Exit(), seen
  383. // the positive numWaitingThread count, and decided that it thus cannot deflate the object
  384. // and will trigger the semaphore. However, we've just decided to give up waiting, so if
  385. // we were the only thread waiting and no one ever attempts to lock the object again, the
  386. // monitor will stick around with no one ever deflating the object.
  387. //
  388. // We solve this by simply trying to acquire ownership of the monitor if we were the last
  389. // waiting thread and if that succeeds, we simply change from returning with a time out
  390. // failure to returning with a successful lock.
  391. if (!newNumWaitingThreads && il2cpp::os::Atomic::ReadPointer(&obj->monitor) == installedMonitor)
  392. {
  393. if (installedMonitor->TryAcquire(currentThreadId))
  394. {
  395. // We've successfully acquired a lock on the object.
  396. IL2CPP_ASSERT(installedMonitor->recursiveLockingCount == 1);
  397. IL2CPP_ASSERT(obj->monitor == installedMonitor);
  398. return true;
  399. }
  400. }
  401. // Catch the case where a timeout expired the very moment the owning thread decided to
  402. // get us to vacate the monitor by sending an acknowledgement just to make sure.
  403. if (il2cpp::os::Atomic::ReadPointer(&obj->monitor) != installedMonitor)
  404. installedMonitor->flushAcknowledged.Set();
  405. return false;
  406. }
  407. }
  408. // Owner has deflated the object and the monitor is no longer associated with the
  409. // object we're trying to lock. Signal to the owner that we acknowledge this and
  410. // move off the monitor.
  411. installedMonitor->VacateDyingMonitor();
  412. }
  413. return false;
  414. }
  415. void Monitor::Exit(Il2CppObject* obj)
  416. {
  417. // Fetch monitor data.
  418. MonitorData* monitor = GetMonitorAndThrowIfNotLockedByCurrentThread(obj);
  419. // We have the object lock. Undo one single invocation of Enter().
  420. int newLockingCount = monitor->recursiveLockingCount - 1;
  421. if (newLockingCount > 0)
  422. {
  423. // Was recursively locked. Lock still held by us.
  424. monitor->recursiveLockingCount = newLockingCount;
  425. return;
  426. }
  427. // See if there are already threads ready to take over the lock.
  428. if (monitor->numThreadsWaitingForSemaphore != 0)
  429. {
  430. // Yes, so relinquish ownership of the object and signal the next thread.
  431. monitor->Unacquire();
  432. monitor->semaphore.Post();
  433. }
  434. else if (monitor->threadsWaitingForPulse)
  435. {
  436. // No, but there's threads waiting for a pulse so we can't deflate the object.
  437. // The wait nodes may already have been abandoned but that is for the pulsing
  438. // and waiting threads to sort out. Either way, if there ever is going to be a
  439. // pulse, *some* thread will get around to looking at this monitor again so all
  440. // we do here is relinquish ownership.
  441. monitor->Unacquire();
  442. // there is a race as follows: T1 is our thread and we own monitor lock
  443. // T1 - checks numThreadsWaitingForSemaphore and sees 0
  444. // T2 - sees T1 has lock. Increments numThreadsWaitingForSemaphore
  445. // T2 - tries to acquire monitor, but we hold it
  446. // T2 - waits on semaphore
  447. // T1 - we unacquire and wait to be pulsed (if Exit is called from Wait)
  448. // Result: deadlock as semaphore is never posted
  449. // Fix: double check 'numThreadsWaitingForSemaphore' after we've unacquired
  450. // Worst case might be an extra post, which will just incur an additional
  451. // pass through the loop with an extra attempt to acquire the monitor with a CAS
  452. if (monitor->numThreadsWaitingForSemaphore != 0)
  453. monitor->semaphore.Post();
  454. }
  455. else
  456. {
  457. // Seems like no other thread is interested in the monitor. Deflate the object.
  458. il2cpp::os::Atomic::ExchangePointer(&obj->monitor, (MonitorData*)NULL);
  459. // At this point the monitor is no longer associated with the object and we cannot safely
  460. // "re-attach" it. We need to make sure that all threads still having a reference to the
  461. // monitor let go of it before we put the monitor back on the free list.
  462. //
  463. // IMPORTANT: We still *own* the monitor at this point. No other thread can acquire it and
  464. // we must not let go of the monitor until we have kicked all other threads off of it.
  465. monitor->flushAcknowledged.Reset();
  466. while (monitor->numThreadsWaitingForSemaphore != 0)
  467. {
  468. monitor->semaphore.Post(monitor->numThreadsWaitingForSemaphore);
  469. // If a thread starts waiting right after we have read numThreadsWaitingForSemaphore,
  470. // we won't release the semaphore enough times. So don't wait spend a long time waiting
  471. // for acknowledgement here.
  472. monitor->flushAcknowledged.Wait(1, false);
  473. }
  474. // IMPORTANT: At this point, all other threads must have either already vacated the monitor or
  475. // be on a path that makes them vacate the monitor next. The latter may happen if a thread
  476. // is stopped right before adding itself to the ready list of our monitor in which case we
  477. // will not see the thread on numThreadsWaitingForSemaphore. If we then put the monitor back
  478. // on the freelist and then afterwards the other thread is resumed, it will still put itself
  479. // on the ready list only to then realize it got the wrong monitor.
  480. // So, even for monitors on the free list, we accept that a thread may temporarily add itself
  481. // to the wrong monitor's ready list as long as all it does it simply remove itself right after
  482. // realizing the mistake.
  483. // Release monitor back to free list.
  484. IL2CPP_ASSERT(monitor->owningThreadId == il2cpp::os::Thread::CurrentThreadId());
  485. monitor->owningThreadId = MonitorData::kHasBeenReturnedToFreeList;
  486. MonitorData::s_FreeList.Release(monitor);
  487. }
  488. }
  489. static void PulseMonitor(Il2CppObject* obj, bool all = false)
  490. {
  491. // Grab monitor.
  492. MonitorData* monitor = GetMonitorAndThrowIfNotLockedByCurrentThread(obj);
  493. bool isFirst = true;
  494. while (true)
  495. {
  496. // Grab next waiting thread, if any.
  497. MonitorData::PulseWaitingListNode* waitNode = monitor->PopNextFromPulseWaitingList();
  498. if (!waitNode)
  499. break;
  500. // Pulse thread.
  501. waitNode->signalWaitingThread.Set();
  502. // Stop if we're only supposed to pulse the one thread.
  503. if (isFirst && !all)
  504. break;
  505. isFirst = false;
  506. }
  507. }
  508. void Monitor::Pulse(Il2CppObject* object)
  509. {
  510. PulseMonitor(object, false);
  511. }
  512. void Monitor::PulseAll(Il2CppObject* object)
  513. {
  514. PulseMonitor(object, true);
  515. }
  516. void Monitor::Wait(Il2CppObject* object)
  517. {
  518. TryWait(object, std::numeric_limits<uint32_t>::max());
  519. }
  520. bool Monitor::TryWait(Il2CppObject* object, uint32_t timeoutMilliseconds)
  521. {
  522. MonitorData* monitor = GetMonitorAndThrowIfNotLockedByCurrentThread(object);
  523. // Undo any recursive locking but remember the count so we can restore it
  524. // after we have re-acquired the lock.
  525. uint32_t oldLockingCount = monitor->recursiveLockingCount;
  526. monitor->recursiveLockingCount = 1;
  527. // Add us to the pulse waiting list for the monitor (except if we won't be
  528. // waiting for a pulse at all).
  529. MonitorData::PulseWaitingListNode* waitNode = NULL;
  530. if (timeoutMilliseconds != 0)
  531. {
  532. waitNode = MonitorData::PulseWaitingListNode::Allocate();
  533. monitor->PushOntoPulseWaitingList(waitNode);
  534. }
  535. // Release the monitor.
  536. Exit(object);
  537. monitor = NULL;
  538. // Wait for pulse (if we either have a timeout or are supposed to
  539. // wait infinitely).
  540. il2cpp::os::WaitStatus pulseWaitStatus = kWaitStatusTimeout;
  541. std::exception_ptr exceptionThrownDuringWait = NULL;
  542. if (timeoutMilliseconds != 0)
  543. {
  544. pulseWaitStatus = kWaitStatusFailure;
  545. try
  546. {
  547. il2cpp::vm::ThreadStateSetter state(il2cpp::vm::kThreadStateWaitSleepJoin);
  548. pulseWaitStatus = waitNode->signalWaitingThread.Wait(timeoutMilliseconds, true);
  549. }
  550. catch (...)
  551. {
  552. // Exception occurred during wait. Remember exception but continue with reacquisition
  553. // and cleanup. We re-throw later.
  554. exceptionThrownDuringWait = std::current_exception();
  555. pulseWaitStatus = kWaitStatusFailure;
  556. }
  557. }
  558. // Reacquire the monitor.
  559. Enter(object);
  560. // Monitor *may* have changed.
  561. monitor = object->monitor;
  562. // Restore recursion count.
  563. monitor->recursiveLockingCount = oldLockingCount;
  564. // Get rid of wait list node.
  565. if (waitNode)
  566. {
  567. // Make sure the node is gone from the wait list. If the pulsing thread already did
  568. // that, this won't do anything.
  569. monitor->RemoveFromPulseWaitingList(waitNode);
  570. // And hand it back for reuse.
  571. waitNode->Release();
  572. waitNode = NULL;
  573. }
  574. // If the wait was interrupted by an exception (most likely a ThreadInterruptedException),
  575. // then re-throw now.
  576. //
  577. // NOTE: We delay this to until after we've gone through the reacquisition sequence as we
  578. // have to guarantee that when Monitor.Wait() exits -- whether successfully or not --, it
  579. // still holds a lock. Otherwise a lock() statement around the Wait() will throw an exception,
  580. // for example.
  581. if (exceptionThrownDuringWait)
  582. std::rethrow_exception(exceptionThrownDuringWait);
  583. ////TODO: According to MSDN, the timeout indicates whether we reacquired the lock in time
  584. //// and not just whether the pulse came in time. Thus the current code is imprecise.
  585. return (pulseWaitStatus != kWaitStatusTimeout);
  586. }
  587. bool Monitor::IsAcquired(Il2CppObject* object)
  588. {
  589. MonitorData* monitor = object->monitor;
  590. if (!monitor)
  591. return false;
  592. return monitor->IsAcquired();
  593. }
  594. bool Monitor::IsOwnedByCurrentThread(Il2CppObject* object)
  595. {
  596. MonitorData* monitor = object->monitor;
  597. if (!monitor)
  598. return false;
  599. return monitor->IsOwnedByThread(il2cpp::os::Thread::CurrentThreadId());
  600. }
  601. } /* namespace vm */
  602. } /* namespace il2cpp */
  603. #endif // IL2CPP_SUPPORT_THREADS