Thread.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. #include "os/c-api/il2cpp-config-platforms.h"
  2. #include "os/Thread.h"
  3. #if IL2CPP_SUPPORT_THREADS
  4. #include "os/Mutex.h"
  5. #include "os/ThreadLocalValue.h"
  6. #if IL2CPP_THREADS_STD
  7. #include "os/Std/ThreadImpl.h"
  8. #elif IL2CPP_TARGET_WINDOWS
  9. #include "os/Win32/ThreadImpl.h"
  10. #elif IL2CPP_THREADS_PTHREAD
  11. #include "os/Posix/ThreadImpl.h"
  12. #else
  13. #include "os/ThreadImpl.h"
  14. #endif
  15. #include "utils/dynamic_array.h"
  16. #include "Baselib.h"
  17. #include "Cpp/ReentrantLock.h"
  18. #include <limits>
  19. namespace il2cpp
  20. {
  21. namespace os
  22. {
  23. /// TLS variable referring to current thread.
  24. static ThreadLocalValue s_CurrentThread;
  25. // TLS variable referring to whether this thread is currently executing Thread::Shutdown
  26. // It is thread local for thread safety
  27. static ThreadLocalValue s_IsCleaningUpThreads;
  28. static baselib::ReentrantLock s_AliveThreadsMutex;
  29. static il2cpp::utils::dynamic_array<Thread*> s_AliveThreads;
  30. int64_t Thread::s_DefaultAffinityMask = kThreadAffinityAll;
  31. static bool GetIsCleaningUpThreads()
  32. {
  33. void* value = NULL;
  34. s_IsCleaningUpThreads.GetValue(&value);
  35. return reinterpret_cast<intptr_t>(value) != 0;
  36. }
  37. static void SetIsCleaningUpThreads(bool value)
  38. {
  39. s_IsCleaningUpThreads.SetValue(reinterpret_cast<void*>(static_cast<intptr_t>(value)));
  40. }
  41. Thread::Thread()
  42. : m_Thread(new ThreadImpl())
  43. , m_State(kThreadCreated)
  44. , m_ThreadExitedEvent(true) // Manual reset event
  45. , m_CleanupFunc(NULL)
  46. , m_CleanupFuncArg(NULL)
  47. {
  48. FastAutoLock lock(&s_AliveThreadsMutex);
  49. s_AliveThreads.push_back(this);
  50. }
  51. Thread::Thread(ThreadImpl* thread)
  52. : m_Thread(thread)
  53. , m_State(kThreadRunning)
  54. , m_ThreadExitedEvent(true) // Manual reset event
  55. , m_CleanupFunc(NULL)
  56. , m_CleanupFuncArg(NULL)
  57. {
  58. FastAutoLock lock(&s_AliveThreadsMutex);
  59. s_AliveThreads.push_back(this);
  60. }
  61. Thread::~Thread()
  62. {
  63. delete m_Thread;
  64. if (!GetIsCleaningUpThreads())
  65. {
  66. FastAutoLock lock(&s_AliveThreadsMutex);
  67. size_t count = s_AliveThreads.size();
  68. for (size_t i = 0; i < count; i++)
  69. {
  70. if (s_AliveThreads[i] == this)
  71. {
  72. s_AliveThreads.erase_swap_back(&s_AliveThreads[i]);
  73. break;
  74. }
  75. }
  76. }
  77. }
  78. void Thread::Init()
  79. {
  80. Thread* thread = GetOrCreateCurrentThread();
  81. if (thread->GetApartment() == kApartmentStateUnknown)
  82. thread->SetApartment(kApartmentStateInMTA);
  83. }
  84. void Thread::Shutdown()
  85. {
  86. Thread* currentThread = GetCurrentThread();
  87. currentThread->SetApartment(kApartmentStateUnknown);
  88. SetIsCleaningUpThreads(true);
  89. FastAutoLock lock(&s_AliveThreadsMutex);
  90. size_t count = s_AliveThreads.size();
  91. for (size_t i = 0; i < count; i++)
  92. {
  93. // If this is not the current thread, wait a bit for it to exit. This will avoid an
  94. // infinite wait on shutdown, but it should give the thread enough time to complete its
  95. // use of the os::Thread object before we delete it. Note that we don't call Join here,
  96. // as we want to explicitly do a non-interruptable wait because we are pretty late in
  97. // the shutdown process. The VM thread code should have already caused any running
  98. // threads to get a thread abort exception, meaning that any running OS threads will
  99. // be exiting soon, with no need to check for APCs.
  100. if (s_AliveThreads[i] != currentThread)
  101. {
  102. s_AliveThreads[i]->m_ThreadExitedEvent.Wait(10, false);
  103. delete s_AliveThreads[i];
  104. }
  105. }
  106. // Wait to delete the current thread last, as waiting on an event may need to access the current thread
  107. delete currentThread;
  108. s_AliveThreads.clear();
  109. SetIsCleaningUpThreads(false);
  110. #if IL2CPP_ENABLE_RELOAD
  111. s_CurrentThread.SetValue(NULL);
  112. #endif
  113. }
  114. Thread::ThreadId Thread::Id()
  115. {
  116. return m_Thread->Id();
  117. }
  118. void Thread::SetName(const char* name)
  119. {
  120. m_Thread->SetName(name);
  121. }
  122. void Thread::SetPriority(ThreadPriority priority)
  123. {
  124. m_Thread->SetPriority(priority);
  125. }
  126. ThreadPriority Thread::GetPriority()
  127. {
  128. return m_Thread->GetPriority();
  129. }
  130. void Thread::SetStackSize(size_t stackSize)
  131. {
  132. m_Thread->SetStackSize(stackSize);
  133. }
  134. int Thread::GetMaxStackSize()
  135. {
  136. return ThreadImpl::GetMaxStackSize();
  137. }
  138. struct StartData
  139. {
  140. Thread* thread;
  141. Thread::StartFunc startFunction;
  142. void* startFunctionArgument;
  143. };
  144. /// Wrapper for the user's thread start function. Sets s_CurrentThread.
  145. void Thread::RunWrapper(void* arg)
  146. {
  147. StartData* data = reinterpret_cast<StartData*>(arg);
  148. // Store thread reference.
  149. Thread* thread = data->thread;
  150. const ApartmentState apartment = thread->GetExplicitApartment();
  151. if (apartment != kApartmentStateUnknown)
  152. {
  153. thread->SetExplicitApartment(kApartmentStateUnknown);
  154. thread->SetApartment(apartment);
  155. }
  156. s_CurrentThread.SetValue(thread);
  157. // Get rid of StartData.
  158. StartFunc startFunction = data->startFunction;
  159. void* startFunctionArgument = data->startFunctionArgument;
  160. delete data;
  161. // Make sure thread exit event is not signaled.
  162. thread->m_ThreadExitedEvent.Reset();
  163. // Run user thread start function.
  164. thread->m_State = kThreadRunning;
  165. startFunction(startFunctionArgument);
  166. thread->m_State = kThreadExited;
  167. thread->SetApartment(kApartmentStateUnknown);
  168. CleanupFunc cleanupFunc = thread->m_CleanupFunc;
  169. void* cleanupFuncArg = thread->m_CleanupFuncArg;
  170. // Signal that we've finished execution.
  171. thread->m_ThreadExitedEvent.Set();
  172. if (cleanupFunc)
  173. cleanupFunc(cleanupFuncArg);
  174. }
  175. ErrorCode Thread::Run(StartFunc func, void* arg)
  176. {
  177. IL2CPP_ASSERT(m_State == kThreadCreated || m_State == kThreadExited);
  178. StartData* startData = new StartData;
  179. startData->startFunction = func;
  180. startData->startFunctionArgument = arg;
  181. startData->thread = this;
  182. return m_Thread->Run(RunWrapper, startData, s_DefaultAffinityMask);
  183. }
  184. WaitStatus Thread::Join()
  185. {
  186. IL2CPP_ASSERT(this != GetCurrentThread() && "Trying to join the current thread will deadlock");
  187. return Join(std::numeric_limits<uint32_t>::max());
  188. }
  189. WaitStatus Thread::Join(uint32_t ms)
  190. {
  191. // Wait for thread exit event.
  192. if (m_ThreadExitedEvent.Wait(ms, true) != kWaitStatusSuccess)
  193. return kWaitStatusFailure;
  194. return kWaitStatusSuccess;
  195. }
  196. void Thread::QueueUserAPC(APCFunc func, void* context)
  197. {
  198. m_Thread->QueueUserAPC(func, context);
  199. }
  200. ApartmentState Thread::GetApartment()
  201. {
  202. #if IL2CPP_THREAD_IMPL_HAS_COM_APARTMENTS
  203. return m_Thread->GetApartment();
  204. #else
  205. return kApartmentStateUnknown;
  206. #endif
  207. }
  208. ApartmentState Thread::GetExplicitApartment()
  209. {
  210. #if IL2CPP_THREAD_IMPL_HAS_COM_APARTMENTS
  211. return m_Thread->GetExplicitApartment();
  212. #else
  213. return kApartmentStateUnknown;
  214. #endif
  215. }
  216. ApartmentState Thread::SetApartment(ApartmentState state)
  217. {
  218. #if IL2CPP_THREAD_IMPL_HAS_COM_APARTMENTS
  219. return m_Thread->SetApartment(state);
  220. #else
  221. NO_UNUSED_WARNING(state);
  222. return GetApartment();
  223. #endif
  224. }
  225. void Thread::SetExplicitApartment(ApartmentState state)
  226. {
  227. #if IL2CPP_THREAD_IMPL_HAS_COM_APARTMENTS
  228. m_Thread->SetExplicitApartment(state);
  229. #else
  230. NO_UNUSED_WARNING(state);
  231. #endif
  232. }
  233. void Thread::Sleep(uint32_t milliseconds, bool interruptible)
  234. {
  235. ThreadImpl::Sleep(milliseconds, interruptible);
  236. }
  237. size_t Thread::CurrentThreadId()
  238. {
  239. return ThreadImpl::CurrentThreadId();
  240. }
  241. Thread* Thread::GetCurrentThread()
  242. {
  243. void* value;
  244. s_CurrentThread.GetValue(&value);
  245. IL2CPP_ASSERT(value != NULL);
  246. return reinterpret_cast<Thread*>(value);
  247. }
  248. bool Thread::HasCurrentThread()
  249. {
  250. void* value;
  251. s_CurrentThread.GetValue(&value);
  252. return value != NULL;
  253. }
  254. Thread* Thread::GetOrCreateCurrentThread()
  255. {
  256. Thread* thread = NULL;
  257. s_CurrentThread.GetValue(reinterpret_cast<void**>(&thread));
  258. if (thread)
  259. return thread;
  260. // The os::Thread object is deallocated in the InternalThread::Thread_free_internal icall, which
  261. // is called from the managed thread finalizer.
  262. thread = new Thread(ThreadImpl::CreateForCurrentThread());
  263. s_CurrentThread.SetValue(thread);
  264. return thread;
  265. }
  266. void Thread::DetachCurrentThread()
  267. {
  268. // PTHREAD cleanup isn't deterministic: it could be that our thread local variables get cleaned up before thread clean up routine runs
  269. #if IL2CPP_DEBUG && !IL2CPP_THREADS_PTHREAD
  270. void* value;
  271. s_CurrentThread.GetValue(&value);
  272. IL2CPP_ASSERT(value != NULL);
  273. #endif
  274. s_CurrentThread.SetValue(NULL);
  275. }
  276. bool Thread::YieldInternal()
  277. {
  278. return ThreadImpl::YieldInternal();
  279. }
  280. void Thread::SetDefaultAffinityMask(int64_t affinityMask)
  281. {
  282. s_DefaultAffinityMask = affinityMask;
  283. }
  284. #if IL2CPP_HAS_NATIVE_THREAD_CLEANUP
  285. void Thread::SetNativeThreadCleanup(ThreadCleanupFunc cleanupFunction)
  286. {
  287. ThreadImpl::SetNativeThreadCleanup(cleanupFunction);
  288. }
  289. void Thread::RegisterCurrentThreadForCleanup(void* arg)
  290. {
  291. ThreadImpl::RegisterCurrentThreadForCleanup(arg);
  292. }
  293. void Thread::UnregisterCurrentThreadForCleanup()
  294. {
  295. ThreadImpl::UnregisterCurrentThreadForCleanup();
  296. }
  297. void Thread::SignalExited()
  298. {
  299. m_ThreadExitedEvent.Set();
  300. }
  301. #endif
  302. }
  303. }
  304. #else
  305. #include <limits.h>
  306. namespace il2cpp
  307. {
  308. namespace os
  309. {
  310. int64_t Thread::s_DefaultAffinityMask = -1;
  311. Thread::Thread()
  312. {
  313. }
  314. Thread::~Thread()
  315. {
  316. }
  317. void Thread::Init()
  318. {
  319. }
  320. void Thread::Shutdown()
  321. {
  322. }
  323. Thread::ThreadId Thread::Id()
  324. {
  325. return 0;
  326. }
  327. void Thread::SetName(const char* name)
  328. {
  329. }
  330. void Thread::SetPriority(ThreadPriority priority)
  331. {
  332. }
  333. ThreadPriority Thread::GetPriority()
  334. {
  335. return kThreadPriorityLowest;
  336. }
  337. void Thread::SetStackSize(size_t stackSize)
  338. {
  339. }
  340. int Thread::GetMaxStackSize()
  341. {
  342. return INT_MAX;
  343. }
  344. void Thread::RunWrapper(void* arg)
  345. {
  346. }
  347. ErrorCode Thread::Run(StartFunc func, void* arg)
  348. {
  349. IL2CPP_ASSERT(0 && "Threads are not enabled for this platform.");
  350. return kErrorCodeSuccess;
  351. }
  352. WaitStatus Thread::Join()
  353. {
  354. IL2CPP_ASSERT(0 && "Threads are not enabled for this platform.");
  355. return kWaitStatusSuccess;
  356. }
  357. WaitStatus Thread::Join(uint32_t ms)
  358. {
  359. IL2CPP_ASSERT(0 && "Threads are not enabled for this platform.");
  360. return kWaitStatusSuccess;
  361. }
  362. void Thread::QueueUserAPC(APCFunc func, void* context)
  363. {
  364. }
  365. ApartmentState Thread::GetApartment()
  366. {
  367. return kApartmentStateUnknown;
  368. }
  369. ApartmentState Thread::GetExplicitApartment()
  370. {
  371. return kApartmentStateUnknown;
  372. }
  373. ApartmentState Thread::SetApartment(ApartmentState state)
  374. {
  375. return kApartmentStateUnknown;
  376. }
  377. void Thread::SetExplicitApartment(ApartmentState state)
  378. {
  379. }
  380. void Thread::Sleep(uint32_t milliseconds, bool interruptible)
  381. {
  382. }
  383. size_t Thread::CurrentThreadId()
  384. {
  385. return 0;
  386. }
  387. Thread* Thread::GetCurrentThread()
  388. {
  389. return NULL;
  390. }
  391. Thread* Thread::GetOrCreateCurrentThread()
  392. {
  393. return NULL;
  394. }
  395. void Thread::DetachCurrentThread()
  396. {
  397. }
  398. bool Thread::YieldInternal()
  399. {
  400. return false;
  401. }
  402. void Thread::SetDefaultAffinityMask(int64_t affinityMask)
  403. {
  404. s_DefaultAffinityMask = affinityMask;
  405. }
  406. #if IL2CPP_HAS_NATIVE_THREAD_CLEANUP
  407. void Thread::SetNativeThreadCleanup(ThreadCleanupFunc cleanupFunction)
  408. {
  409. }
  410. void Thread::RegisterCurrentThreadForCleanup(void* arg)
  411. {
  412. }
  413. void Thread::UnregisterCurrentThreadForCleanup()
  414. {
  415. }
  416. void Thread::SignalExited()
  417. {
  418. }
  419. #endif
  420. }
  421. }
  422. #endif