ThreadEmulation.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
  2. // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
  3. // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
  4. // PARTICULAR PURPOSE.
  5. //
  6. // Copyright (c) Microsoft Corporation. All rights reserved.
  7. #include "ThreadEmulation.h"
  8. #include <assert.h>
  9. #include <vector>
  10. #include <set>
  11. #include <map>
  12. #include <mutex>
  13. using namespace std;
  14. using namespace Platform;
  15. using namespace Windows::Foundation;
  16. using namespace Windows::System::Threading;
  17. namespace ThreadEmulation
  18. {
  19. // Stored data for CREATE_SUSPENDED and ResumeThread.
  20. struct PendingThreadInfo
  21. {
  22. LPTHREAD_START_ROUTINE lpStartAddress;
  23. LPVOID lpParameter;
  24. HANDLE completionEvent;
  25. int nPriority;
  26. };
  27. static map<HANDLE, PendingThreadInfo> pendingThreads;
  28. static mutex pendingThreadsLock;
  29. // Thread local storage.
  30. typedef vector<void*> ThreadLocalData;
  31. static __declspec(thread) ThreadLocalData* currentThreadData = nullptr;
  32. static set<ThreadLocalData*> allThreadData;
  33. static DWORD nextTlsIndex = 0;
  34. static vector<DWORD> freeTlsIndices;
  35. static mutex tlsAllocationLock;
  36. // Converts a Win32 thread priority to WinRT format.
  37. static WorkItemPriority GetWorkItemPriority(int nPriority)
  38. {
  39. if (nPriority < 0)
  40. return WorkItemPriority::Low;
  41. else if (nPriority > 0)
  42. return WorkItemPriority::High;
  43. else
  44. return WorkItemPriority::Normal;
  45. }
  46. // Helper shared between CreateThread and ResumeThread.
  47. static void StartThread(LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, HANDLE completionEvent, int nPriority)
  48. {
  49. auto workItemHandler = ref new WorkItemHandler([=](IAsyncAction^)
  50. {
  51. // Run the user callback.
  52. try
  53. {
  54. lpStartAddress(lpParameter);
  55. }
  56. catch (Exception ^e)
  57. {
  58. Platform::String ^exceptionString = e->ToString();
  59. OutputDebugStringW(exceptionString->Data());
  60. }
  61. // Clean up any TLS allocations made by this thread.
  62. TlsShutdown();
  63. // Signal that the thread has completed.
  64. SetEvent(completionEvent);
  65. CloseHandle(completionEvent);
  66. }, CallbackContext::Any);
  67. ThreadPool::RunAsync(workItemHandler, GetWorkItemPriority(nPriority), WorkItemOptions::TimeSliced);
  68. }
  69. _Use_decl_annotations_ HANDLE WINAPI CreateThread(LPSECURITY_ATTRIBUTES unusedThreadAttributes, SIZE_T unusedStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD unusedThreadId)
  70. {
  71. // Validate parameters.
  72. assert(unusedThreadAttributes == nullptr);
  73. assert(unusedStackSize == 0);
  74. assert((dwCreationFlags & ~CREATE_SUSPENDED) == 0);
  75. assert(unusedThreadId == nullptr);
  76. // Create a handle that will be signalled when the thread has completed.
  77. HANDLE threadHandle = CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, EVENT_ALL_ACCESS);
  78. if (!threadHandle)
  79. return nullptr;
  80. // Make a copy of the handle for internal use. This is necessary because
  81. // the caller is responsible for closing the handle returned by CreateThread,
  82. // and they may do that before or after the thread has finished running.
  83. HANDLE completionEvent;
  84. if (!DuplicateHandle(GetCurrentProcess(), threadHandle, GetCurrentProcess(), &completionEvent, 0, false, DUPLICATE_SAME_ACCESS))
  85. {
  86. CloseHandle(threadHandle);
  87. return nullptr;
  88. }
  89. try
  90. {
  91. if (dwCreationFlags & CREATE_SUSPENDED)
  92. {
  93. // Store info about a suspended thread.
  94. PendingThreadInfo info;
  95. info.lpStartAddress = lpStartAddress;
  96. info.lpParameter = lpParameter;
  97. info.completionEvent = completionEvent;
  98. info.nPriority = 0;
  99. lock_guard<mutex> lock(pendingThreadsLock);
  100. pendingThreads[threadHandle] = info;
  101. }
  102. else
  103. {
  104. // Start the thread immediately.
  105. StartThread(lpStartAddress, lpParameter, completionEvent, 0);
  106. }
  107. return threadHandle;
  108. }
  109. catch (...)
  110. {
  111. // Clean up if thread creation fails.
  112. CloseHandle(threadHandle);
  113. CloseHandle(completionEvent);
  114. return nullptr;
  115. }
  116. }
  117. _Use_decl_annotations_ DWORD WINAPI ResumeThread(HANDLE hThread)
  118. {
  119. lock_guard<mutex> lock(pendingThreadsLock);
  120. // Look up the requested thread.
  121. auto threadInfo = pendingThreads.find(hThread);
  122. if (threadInfo == pendingThreads.end())
  123. {
  124. // Can only resume threads while they are in CREATE_SUSPENDED state.
  125. assert(false);
  126. return (DWORD)-1;
  127. }
  128. // Start the thread.
  129. try
  130. {
  131. PendingThreadInfo& info = threadInfo->second;
  132. StartThread(info.lpStartAddress, info.lpParameter, info.completionEvent, info.nPriority);
  133. }
  134. catch (...)
  135. {
  136. return (DWORD)-1;
  137. }
  138. // Remove this thread from the pending list.
  139. pendingThreads.erase(threadInfo);
  140. return 0;
  141. }
  142. _Use_decl_annotations_ BOOL WINAPI SetThreadPriority(HANDLE hThread, int nPriority)
  143. {
  144. lock_guard<mutex> lock(pendingThreadsLock);
  145. // Look up the requested thread.
  146. auto threadInfo = pendingThreads.find(hThread);
  147. if (threadInfo == pendingThreads.end())
  148. {
  149. // Can only set priority on threads while they are in CREATE_SUSPENDED state.
  150. assert(false);
  151. return false;
  152. }
  153. // Store the new priority.
  154. threadInfo->second.nPriority = nPriority;
  155. return true;
  156. }
  157. _Use_decl_annotations_ VOID WINAPI Sleep(DWORD dwMilliseconds)
  158. {
  159. static HANDLE singletonEvent = nullptr;
  160. HANDLE sleepEvent = singletonEvent;
  161. // Demand create the event.
  162. if (!sleepEvent)
  163. {
  164. sleepEvent = CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, EVENT_ALL_ACCESS);
  165. if (!sleepEvent)
  166. return;
  167. HANDLE previousEvent = InterlockedCompareExchangePointerRelease(&singletonEvent, sleepEvent, nullptr);
  168. if (previousEvent)
  169. {
  170. // Back out if multiple threads try to demand create at the same time.
  171. CloseHandle(sleepEvent);
  172. sleepEvent = previousEvent;
  173. }
  174. }
  175. // Emulate sleep by waiting with timeout on an event that is never signalled.
  176. WaitForSingleObjectEx(sleepEvent, dwMilliseconds, false);
  177. }
  178. DWORD WINAPI TlsAlloc()
  179. {
  180. lock_guard<mutex> lock(tlsAllocationLock);
  181. // Can we reuse a previously freed TLS slot?
  182. if (!freeTlsIndices.empty())
  183. {
  184. DWORD result = freeTlsIndices.back();
  185. freeTlsIndices.pop_back();
  186. return result;
  187. }
  188. // Allocate a new TLS slot.
  189. return nextTlsIndex++;
  190. }
  191. _Use_decl_annotations_ BOOL WINAPI TlsFree(DWORD dwTlsIndex)
  192. {
  193. lock_guard<mutex> lock(tlsAllocationLock);
  194. assert(dwTlsIndex < nextTlsIndex);
  195. assert(find(freeTlsIndices.begin(), freeTlsIndices.end(), dwTlsIndex) == freeTlsIndices.end());
  196. // Store this slot for reuse by TlsAlloc.
  197. try
  198. {
  199. freeTlsIndices.push_back(dwTlsIndex);
  200. }
  201. catch (...)
  202. {
  203. return false;
  204. }
  205. // Zero the value for all threads that might be using this now freed slot.
  206. for each (auto threadData in allThreadData)
  207. {
  208. if (threadData->size() > dwTlsIndex)
  209. {
  210. threadData->at(dwTlsIndex) = nullptr;
  211. }
  212. }
  213. return true;
  214. }
  215. _Use_decl_annotations_ LPVOID WINAPI TlsGetValue(DWORD dwTlsIndex)
  216. {
  217. ThreadLocalData* threadData = currentThreadData;
  218. if (threadData && threadData->size() > dwTlsIndex)
  219. {
  220. // Return the value of an allocated TLS slot.
  221. return threadData->at(dwTlsIndex);
  222. }
  223. else
  224. {
  225. // Default value for unallocated slots.
  226. return nullptr;
  227. }
  228. }
  229. _Use_decl_annotations_ BOOL WINAPI TlsSetValue(DWORD dwTlsIndex, LPVOID lpTlsValue)
  230. {
  231. ThreadLocalData* threadData = currentThreadData;
  232. if (!threadData)
  233. {
  234. // First time allocation of TLS data for this thread.
  235. try
  236. {
  237. threadData = new ThreadLocalData(dwTlsIndex + 1, nullptr);
  238. lock_guard<mutex> lock(tlsAllocationLock);
  239. allThreadData.insert(threadData);
  240. currentThreadData = threadData;
  241. }
  242. catch (...)
  243. {
  244. if (threadData)
  245. delete threadData;
  246. return false;
  247. }
  248. }
  249. else if (threadData->size() <= dwTlsIndex)
  250. {
  251. // This thread already has a TLS data block, but it must be expanded to fit the specified slot.
  252. try
  253. {
  254. lock_guard<mutex> lock(tlsAllocationLock);
  255. threadData->resize(dwTlsIndex + 1, nullptr);
  256. }
  257. catch (...)
  258. {
  259. return false;
  260. }
  261. }
  262. // Store the new value for this slot.
  263. threadData->at(dwTlsIndex) = lpTlsValue;
  264. return true;
  265. }
  266. // Called at thread exit to clean up TLS allocations.
  267. void WINAPI TlsShutdown()
  268. {
  269. ThreadLocalData* threadData = currentThreadData;
  270. if (threadData)
  271. {
  272. {
  273. lock_guard<mutex> lock(tlsAllocationLock);
  274. allThreadData.erase(threadData);
  275. }
  276. currentThreadData = nullptr;
  277. delete threadData;
  278. }
  279. }
  280. }
粤ICP备19079148号