WaitObject.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. #include "il2cpp-config.h"
  2. #if (IL2CPP_THREADS_PTHREAD || IL2CPP_THREADS_WIN32) && !RUNTIME_TINY
  3. #include "WaitObject.h"
  4. #include "os/Time.h"
  5. #if IL2CPP_THREADS_WIN32
  6. #include "os/Win32/ThreadImpl.h"
  7. #else
  8. #include "os/Posix/ThreadImpl.h"
  9. #endif
  10. // Notes:
  11. // ************************************ Old notes here ************************************
  12. // - Situation
  13. // - None of the pthread APIs are interruptible (they all explicitly forbid returning EINTR).
  14. // - We cannot do any non-local transfers of control from signal handlers safely (C++ exceptions
  15. // or longjmp). Thus we cannot use signals to inject interruptions into a thread.
  16. // - Very few of the system APIs we have available support timeouts (at least not on all platforms).
  17. // - Ergo: we need to roll our own synchronization primitives based on pthread condition variables
  18. // (they support timeouts and have the functionality needed to model the other primitives).
  19. // - BUT: the condition variables still involve mutexes which we cannot lock in way that allows
  20. // interruptions. This means that there will be time windows where threads will wait and just
  21. // block and not allow interruption.
  22. //
  23. // ************************************ Old notes above ************************************
  24. /*
  25. Pthread api functions has been replaced by baselib sync primitives
  26. Condition variable is simulated by using a baselib capped semaphore in the thread itself and a baselib lock
  27. which is part of our sync primitive. If a thread waits for a condition we first take the lock and tell
  28. current thread to save 'us' as a wait object and then go into the simulated condition variable.
  29. Our condition variable first registers the thread as a waiter to be used when waking up threads.
  30. This list is a shared resource but we already have acquired the lock. Then we acquire the capped semaphore
  31. on the thread side of things that will either put us to sleep or carry on as normal if the semaphore has been signalled already.
  32. Once the thread wakes up, either from an APC or otherwise, it will re-acquire the lock and check for pending APCs
  33. and then if the condition itself (m_Count is 0) has been met.
  34. If an APC is queued we save the request (a callback and context) on the thread side and release/signal the semaphore to wakeup the thread. Once awake we
  35. call into the thread to process the APC by invoking the callback which once done will throw an exception which is then caught by WaitObject::Wait()
  36. and we exit the wait.
  37. */
  38. namespace il2cpp
  39. {
  40. namespace os
  41. {
  42. WaitObject::WaitObject(Type type)
  43. : m_Type(type)
  44. , m_Count(0)
  45. , m_WaitingThreadCount(0)
  46. {
  47. }
  48. WaitObject::~WaitObject()
  49. {
  50. }
  51. WaitStatus WaitObject::Wait(bool interruptible)
  52. {
  53. return Wait(kNoTimeout, interruptible);
  54. }
  55. WaitStatus WaitObject::Wait(uint32_t timeoutMS, bool interruptible)
  56. {
  57. // IMPORTANT: This function must be exception-safe! APCs may throw.
  58. ThreadImpl* currentThread = ThreadImpl::GetCurrentThread();
  59. // Do up-front check about pending APC except this is a zero-timeout
  60. // wait (i.e. a wait that is never supposed to block and thus go into
  61. // an interruptible state).
  62. if (interruptible && timeoutMS != 0)
  63. currentThread->CheckForUserAPCAndHandle();
  64. // Lock object. We release this mutex during waiting.
  65. ReleaseOnDestroy lock(m_Mutex);
  66. // See if the object is in a state where we can acquire it right away.
  67. if (m_Count == 0)
  68. {
  69. // No, hasn't. If we're not supposed to wait, we're done.
  70. if (timeoutMS == 0)
  71. return kWaitStatusTimeout;
  72. try
  73. {
  74. // We should wait. Let the world know this thread is now waiting
  75. // on this object.
  76. if (interruptible)
  77. currentThread->SetWaitObject(this);
  78. // Check APC queue again to avoid race condition.
  79. if (interruptible)
  80. currentThread->CheckForUserAPCAndHandle();
  81. // Go into wait until we either have a release or timeout or otherwise fail.
  82. int32_t remainingWaitTime = (int32_t)timeoutMS;
  83. WaitStatus waitStatus = kWaitStatusSuccess;
  84. while (m_Count == 0)
  85. {
  86. if (timeoutMS == kNoTimeout)
  87. {
  88. // Infinite wait. Can only be interrupted by APC.
  89. ++m_WaitingThreadCount; // No synchronization necessary; we hold the mutex.
  90. ConditionWait(currentThread);
  91. --m_WaitingThreadCount;
  92. }
  93. else
  94. {
  95. // Timed wait. Can be interrupted by APC or timeout.
  96. const int64_t waitStartTime = Time::GetTicks100NanosecondsMonotonic();
  97. ++m_WaitingThreadCount;
  98. bool wait_timedout = ConditionTimedWait(currentThread, remainingWaitTime);
  99. --m_WaitingThreadCount; ////TODO: make this atomic for when we fail to reacquire the mutex
  100. if (wait_timedout == false)
  101. {
  102. waitStatus = kWaitStatusTimeout;
  103. break;
  104. }
  105. // Update time we have have left to wait.
  106. const int32_t waitTimeThisRound = (int32_t)(Time::GetTicks100NanosecondsMonotonic() - waitStartTime) / 10000;
  107. if (waitTimeThisRound > remainingWaitTime)
  108. remainingWaitTime = 0;
  109. else
  110. remainingWaitTime -= waitTimeThisRound;
  111. }
  112. // We've received a signal but it may be because of an APC and not because
  113. // the semaphore got signaled. If so, handle the APC and go back to waiting.
  114. if (interruptible)
  115. currentThread->CheckForUserAPCAndHandle();
  116. }
  117. // We're done waiting so untie us from the current thread.
  118. // NOTE: A thread may have grabbed us and then got paused. If we return now and then our owner
  119. // tries to delete us, we would pull the rug from under the other thread. This is prevented by
  120. // having a central lock on wait object deletion which any thread trying to deal with wait
  121. // objects from other threads has to acquire.
  122. if (interruptible)
  123. {
  124. currentThread->SetWaitObject(NULL);
  125. // Avoid race condition by checking APC queue again after unsetting wait object.
  126. currentThread->CheckForUserAPCAndHandle();
  127. }
  128. // If we failed, bail out now.
  129. if (waitStatus != kWaitStatusSuccess)
  130. return waitStatus;
  131. }
  132. catch (...)
  133. {
  134. if (interruptible)
  135. currentThread->SetWaitObject(NULL);
  136. throw;
  137. }
  138. }
  139. // At this point, we should be in signaled state and have the lock on
  140. // the object.
  141. // Object has been released. Acquire it for this thread.
  142. IL2CPP_ASSERT(m_Count > 0);
  143. switch (m_Type)
  144. {
  145. case kManualResetEvent:
  146. // Nothing to do.
  147. break;
  148. case kMutex:
  149. case kAutoResetEvent:
  150. m_Count = 0;
  151. break;
  152. case kSemaphore:
  153. if (m_Count > 0) // Defensive.
  154. {
  155. --m_Count;
  156. if (m_Count > 0)
  157. {
  158. // There's more releases on the semaphore. Signal the next thread in line.
  159. if (HaveWaitingThreads())
  160. WakeupOneThread();
  161. }
  162. }
  163. break;
  164. }
  165. return kWaitStatusSuccess;
  166. }
  167. // Register this thread as a waiter to be notified
  168. void WaitObject::PushThreadToWaitersList(WaitObject* owner, ThreadImpl* thread)
  169. {
  170. SThreadPairPosix pair(thread, owner);
  171. m_WaitingThreads.push_back(pair);
  172. }
  173. // Unregister this thread
  174. void WaitObject::PopThreadFromWaitersList(ThreadImpl* thread)
  175. {
  176. auto it = m_WaitingThreads.begin();
  177. while (it != m_WaitingThreads.end())
  178. {
  179. if ((*it).thread == thread)
  180. {
  181. m_WaitingThreads.erase_swap_back(it);
  182. break;
  183. }
  184. else
  185. ++it;
  186. }
  187. }
  188. void WaitObject::ConditionWait(ThreadImpl* thread)
  189. {
  190. PushThreadToWaitersList(this, thread);
  191. m_Mutex.Release();
  192. thread->AcquireSemaphore();
  193. m_Mutex.Acquire();
  194. PopThreadFromWaitersList(thread);
  195. }
  196. bool WaitObject::ConditionTimedWait(ThreadImpl* thread, uint32_t timeout)
  197. {
  198. PushThreadToWaitersList(this, thread);
  199. m_Mutex.Release();
  200. bool ret = thread->TryTimedAcquireSemaphore(timeout);
  201. m_Mutex.Acquire();
  202. PopThreadFromWaitersList(thread);
  203. return ret;
  204. }
  205. void WaitObject::WakeupThreads(bool wakeupOneThread)
  206. {
  207. // Wake up threads.
  208. // We do this by iterating the waiters list and check if the owner (the semaphore, event or mutex) matches 'this'
  209. // ie who is waiting for us specifically
  210. // Mutex must be locked already by caller, see EventImpl::Set(), SemaphoreImpl::Post() and EventImpl::Set()
  211. IL2CPP_ASSERT(m_Mutex.TryAcquire() == false);
  212. int threadsWaiting = (int)m_WaitingThreads.size();
  213. int threadsNotified = 0;
  214. for (int i = 0; i < threadsWaiting; i++)
  215. {
  216. SThreadPairPosix* object = &m_WaitingThreads[i];
  217. if (object->owner == this)
  218. {
  219. // a thread is stuck waiting for us, signal the thread semaphore
  220. object->thread->ReleaseSemaphore();
  221. // if only one wakeup is requested we exit here
  222. if (wakeupOneThread)
  223. break;
  224. }
  225. }
  226. }
  227. void* WaitObject::GetOSHandle()
  228. {
  229. IL2CPP_ASSERT(0 && "This function is not implemented and should not be called");
  230. return NULL;
  231. }
  232. }
  233. }
  234. #endif // IL2CPP_TARGET_POSIX