暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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