threadWin32Impl.cxx 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. /**
  2. * PANDA 3D SOFTWARE
  3. * Copyright (c) Carnegie Mellon University. All rights reserved.
  4. *
  5. * All use of this software is subject to the terms of the revised BSD
  6. * license. You should have received a copy of this license along
  7. * with this source code in a file named "LICENSE."
  8. *
  9. * @file threadWin32Impl.cxx
  10. * @author drose
  11. * @date 2006-02-07
  12. */
  13. #include "threadWin32Impl.h"
  14. #include "selectThreadImpl.h"
  15. #ifdef THREAD_WIN32_IMPL
  16. #include "thread.h"
  17. #include "pointerTo.h"
  18. #include "config_pipeline.h"
  19. #include <windows.h>
  20. static thread_local Thread *_current_thread = nullptr;
  21. static patomic_flag _main_thread_known = ATOMIC_FLAG_INIT;
  22. #if _WIN32_WINNT < 0x0601
  23. // Requires Windows 7.
  24. static DWORD (*EnableThreadProfiling)(HANDLE, DWORD, DWORD64, HANDLE *) = nullptr;
  25. static DWORD (*DisableThreadProfiling)(HANDLE) = nullptr;
  26. static DWORD (*ReadThreadProfilingData)(HANDLE, DWORD, PPERFORMANCE_DATA data) = nullptr;
  27. static bool init_thread_profiling() {
  28. static bool inited = false;
  29. if (!inited) {
  30. HMODULE kernel32 = GetModuleHandleA("kernel32.dll");
  31. EnableThreadProfiling = (decltype(EnableThreadProfiling))GetProcAddress(kernel32, "EnableThreadProfiling");
  32. DisableThreadProfiling = (decltype(DisableThreadProfiling))GetProcAddress(kernel32, "DisableThreadProfiling");
  33. ReadThreadProfilingData = (decltype(ReadThreadProfilingData))GetProcAddress(kernel32, "ReadThreadProfilingData");
  34. inited = true;
  35. }
  36. return (EnableThreadProfiling && DisableThreadProfiling && ReadThreadProfilingData);
  37. }
  38. #else
  39. static bool init_thread_profiling() {
  40. return true;
  41. }
  42. #endif
  43. /**
  44. * Called by get_current_thread() if the current thread pointer is null; checks
  45. * whether it might be the main thread.
  46. * Note that adding noinline speeds up this call *significantly*, don't remove!
  47. */
  48. static __declspec(noinline) Thread *
  49. init_current_thread() {
  50. Thread *thread = _current_thread;
  51. if (!_main_thread_known.test_and_set(std::memory_order_relaxed)) {
  52. // Assume that we must be in the main thread, since this method must be
  53. // called before the first thread is spawned.
  54. thread = Thread::get_main_thread();
  55. _current_thread = thread;
  56. }
  57. // If this assertion triggers, you are making Panda calls from a thread
  58. // that has not first been registered using Thread::bind_thread().
  59. nassertr(thread != nullptr, nullptr);
  60. return thread;
  61. }
  62. /**
  63. *
  64. */
  65. ThreadWin32Impl::
  66. ~ThreadWin32Impl() {
  67. if (thread_cat->is_debug()) {
  68. thread_cat.debug() << "Deleting thread " << _parent_obj->get_name() << "\n";
  69. }
  70. CloseHandle(_thread);
  71. }
  72. /**
  73. * Called for the main thread only, which has been already started, to fill in
  74. * the values appropriate to that thread.
  75. */
  76. void ThreadWin32Impl::
  77. setup_main_thread() {
  78. _status = S_running;
  79. }
  80. /**
  81. *
  82. */
  83. bool ThreadWin32Impl::
  84. start(ThreadPriority priority, bool joinable) {
  85. _mutex.lock();
  86. if (thread_cat->is_debug()) {
  87. thread_cat.debug() << "Starting " << *_parent_obj << "\n";
  88. }
  89. nassertd(_status == S_new && _thread == 0) {
  90. _mutex.unlock();
  91. return false;
  92. }
  93. _joinable = joinable;
  94. _status = S_start_called;
  95. // Increment the parent object's reference count first. The thread will
  96. // eventually decrement it when it terminates.
  97. _parent_obj->ref();
  98. _thread =
  99. CreateThread(nullptr, 0, &root_func, (void *)this, 0, &_thread_id);
  100. if (_thread_id == 0) {
  101. // Oops, we couldn't start the thread. Be sure to decrement the reference
  102. // count we incremented above, and return false to indicate failure.
  103. unref_delete(_parent_obj);
  104. _mutex.unlock();
  105. return false;
  106. }
  107. // Thread was successfully started. Set the priority as specified.
  108. switch (priority) {
  109. case TP_low:
  110. SetThreadPriority(_thread, THREAD_PRIORITY_BELOW_NORMAL);
  111. break;
  112. case TP_high:
  113. SetThreadPriority(_thread, THREAD_PRIORITY_ABOVE_NORMAL);
  114. break;
  115. case TP_urgent:
  116. SetThreadPriority(_thread, THREAD_PRIORITY_HIGHEST);
  117. break;
  118. case TP_normal:
  119. default:
  120. SetThreadPriority(_thread, THREAD_PRIORITY_NORMAL);
  121. break;
  122. }
  123. _mutex.unlock();
  124. return true;
  125. }
  126. /**
  127. * Blocks the calling process until the thread terminates. If the thread has
  128. * already terminated, this returns immediately.
  129. */
  130. void ThreadWin32Impl::
  131. join() {
  132. _mutex.lock();
  133. nassertd(_joinable && _status != S_new) {
  134. _mutex.unlock();
  135. return;
  136. }
  137. while (_status != S_finished) {
  138. _cv.wait();
  139. }
  140. _mutex.unlock();
  141. }
  142. /**
  143. *
  144. */
  145. std::string ThreadWin32Impl::
  146. get_unique_id() const {
  147. std::ostringstream strm;
  148. strm << GetCurrentProcessId() << "." << _thread_id;
  149. return strm.str();
  150. }
  151. /**
  152. *
  153. */
  154. Thread *ThreadWin32Impl::
  155. get_current_thread() {
  156. Thread *thread = _current_thread;
  157. return (thread != nullptr) ? thread : init_current_thread();
  158. }
  159. /**
  160. * Associates the indicated Thread object with the currently-executing thread.
  161. * You should not call this directly; use Thread::bind_thread() instead.
  162. */
  163. void ThreadWin32Impl::
  164. bind_thread(Thread *thread) {
  165. if (_current_thread == nullptr && thread == Thread::get_main_thread()) {
  166. _main_thread_known.test_and_set(std::memory_order_relaxed);
  167. }
  168. _current_thread = thread;
  169. }
  170. /**
  171. * Returns the number of context switches that occurred on the current thread.
  172. * The first number is the total number of context switches reported by the OS,
  173. * and the second number is the number of involuntary context switches (ie. the
  174. * thread was scheduled out by the OS), if known, otherwise zero.
  175. * Returns true if context switch information was available, false otherwise.
  176. */
  177. bool ThreadWin32Impl::
  178. get_context_switches(size_t &total, size_t &involuntary) {
  179. Thread *thread = get_current_thread();
  180. ThreadWin32Impl *self = &thread->_impl;
  181. if (!self->_profiling && init_thread_profiling()) {
  182. DWORD result = EnableThreadProfiling(GetCurrentThread(), THREAD_PROFILING_FLAG_DISPATCH, 0, &self->_profiling);
  183. if (result != ERROR_SUCCESS) {
  184. self->_profiling = 0;
  185. return false;
  186. }
  187. }
  188. PERFORMANCE_DATA data = {sizeof(PERFORMANCE_DATA), PERFORMANCE_DATA_VERSION};
  189. if (ReadThreadProfilingData(self->_profiling, READ_THREAD_PROFILING_FLAG_DISPATCHING, &data) == ERROR_SUCCESS) {
  190. total = data.ContextSwitchCount;
  191. involuntary = 0;
  192. return true;
  193. }
  194. return false;
  195. }
  196. /**
  197. * The entry point of each thread.
  198. */
  199. DWORD ThreadWin32Impl::
  200. root_func(LPVOID data) {
  201. TAU_REGISTER_THREAD();
  202. {
  203. // TAU_PROFILE("void ThreadWin32Impl::root_func()", " ", TAU_USER);
  204. ThreadWin32Impl *self = (ThreadWin32Impl *)data;
  205. _current_thread = self->_parent_obj;
  206. {
  207. self->_mutex.lock();
  208. nassertd(self->_status == S_start_called) {
  209. self->_mutex.unlock();
  210. return 1;
  211. }
  212. self->_status = S_running;
  213. self->_cv.notify();
  214. self->_mutex.unlock();
  215. }
  216. self->_parent_obj->thread_main();
  217. if (thread_cat->is_debug()) {
  218. thread_cat.debug()
  219. << "Terminating thread " << self->_parent_obj->get_name()
  220. << ", count = " << self->_parent_obj->get_ref_count() << "\n";
  221. }
  222. {
  223. self->_mutex.lock();
  224. nassertd(self->_status == S_running) {
  225. self->_mutex.unlock();
  226. return 1;
  227. }
  228. self->_status = S_finished;
  229. self->_cv.notify();
  230. self->_mutex.unlock();
  231. }
  232. if (self->_profiling != 0) {
  233. DisableThreadProfiling(self->_profiling);
  234. self->_profiling = 0;
  235. }
  236. // Now drop the parent object reference that we grabbed in start(). This
  237. // might delete the parent object, and in turn, delete the ThreadWin32Impl
  238. // object.
  239. unref_delete(self->_parent_obj);
  240. }
  241. return 0;
  242. }
  243. #endif // THREAD_WIN32_IMPL