Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. // threading.cpp
  2. //
  3. // Copyright (C) 2006-2020 MicroNeil Research Corporation.
  4. //
  5. // This software is released under the MIT license. See LICENSE.TXT.
  6. #include "threading.hpp"
  7. namespace codedweller {
  8. ThreadManager Threads; // Master thread manager.
  9. void ThreadManager::rememberThread(Thread* T) { // Threads register themselves.
  10. ScopeMutex ThereCanBeOnlyOne(MyMutex); // Protect the known pool.
  11. KnownThreads.insert(T); // Add the new thread pointer.
  12. }
  13. void ThreadManager::forgetThread(Thread* T) { // Threads remove themselves.
  14. ScopeMutex ThereCanBeOnlyOne(MyMutex); // Protect the known pool.
  15. KnownThreads.erase(T); // Add the new thread pointer.
  16. }
  17. ThreadStatusReport ThreadManager::StatusReport() { // Get a status report, All Threads.
  18. ScopeMutex ThereCanBeOnlyOne(MyMutex); // Protect our set -- a moment in time.
  19. ThreadStatusReport Answer; // Create our vector to hold the report.
  20. for( // Loop through all of the Threads.
  21. std::set<Thread*>::iterator iT = KnownThreads.begin();
  22. iT != KnownThreads.end(); iT++
  23. ) { // Grab each Threads' report.
  24. Thread& X = *(*iT); // Handy reference to the Thread.
  25. Answer.push_back(X.StatusReport()); // Push back each Thread's report.
  26. }
  27. return Answer; // Return the finished report.
  28. }
  29. bool ThreadManager::lockExistingThread(Thread* T) { // Locks ThreadManager if T exists.
  30. MyMutex.lock(); // Lock the mutex for everyone.
  31. if(KnownThreads.end() == KnownThreads.find(T)) { // If we do not find T in our set
  32. MyMutex.unlock(); // then unlock the mutex and return
  33. return false; // false.
  34. } // If we did find it then
  35. LockedThread = T; // set our locked thread and
  36. return true; // return true;
  37. }
  38. const RuntimeCheck ThreadingCheck1("ThreadManager::unlockExistingThread():ThreadingCheck1(0 != LockedThread)");
  39. const RuntimeCheck ThreadingCheck2("ThreadManager::unlockExistingThread():ThreadingCheck2(T == LockedThread)");
  40. void ThreadManager::unlockExistingThread(Thread* T) { // Unlocks ThreadManager if T locked.
  41. ThreadingCheck1(0 != LockedThread); // We had better have a locked thread.
  42. ThreadingCheck2(T == LockedThread); // The locked thread had better match.
  43. LockedThread = 0; // Clear the locked thread.
  44. MyMutex.unlock(); // Unlock the mutex.
  45. }
  46. //// Scope Thread Lock allows for a safe way to lock threads through the Threads
  47. //// object for delivering short messages. Just like a ScopeMutex, when the object
  48. //// goes away the lock is released.
  49. ScopeThreadLock::ScopeThreadLock(Thread* T) : // Construct a scope lock on a Thread.
  50. MyLockedThread(0) { // To star with we have no lock.
  51. if(Threads.lockExistingThread(T)) { // If we achieve a lock then we
  52. MyLockedThread = T; // remember it. Our destructor will
  53. } // unlock it if we were successful.
  54. }
  55. ScopeThreadLock::~ScopeThreadLock() { // Destruct a scope lock on a Thread.
  56. if(0 != MyLockedThread) { // If we were successfully constructed
  57. Threads.unlockExistingThread(MyLockedThread); // we can unlock the thread and
  58. MyLockedThread = 0; // forget about it before we go away.
  59. }
  60. }
  61. bool ScopeThreadLock::isGood() { // If we have successfully locked T
  62. return (0 != MyLockedThread) ? true:false; // it will NOT be 0, so return true.
  63. }
  64. bool ScopeThreadLock::isBad() { // If we did not successfully lock T
  65. return (0 == MyLockedThread) ? false:true; // it will be 0, so return false.
  66. }
  67. ////////////////////////////////////////////////////////////////////////////////
  68. // Thread
  69. const ThreadType Thread::Type("Generic Thread");
  70. const ThreadState Thread::ThreadInitialized("Thread Initialized");
  71. const ThreadState Thread::ThreadStarted("Thread Started");
  72. const ThreadState Thread::ThreadFailed("Thread Failed");
  73. const ThreadState Thread::ThreadStopped("Thread Stopped");
  74. const ThreadState Thread::ThreadDestroyed("Thread Destroyed");
  75. bool Thread::isRunning() { return RunningFlag; } // Return RunningFlag state.
  76. bool Thread::isBad() { return BadFlag; } // Return BadFlag state.
  77. const std::string Thread::MyFault() { return BadWhat; } // Return exception Bad fault if any.
  78. const std::string Thread::MyName() { return MyThreadName; } // Return the instance name if any.
  79. const ThreadType& Thread::MyType() { return MyThreadType; } // Return the instance Thread Type.
  80. const ThreadState& Thread::MyState() { return (*MyThreadState); } // Thread state for this instance.
  81. void Thread::CurrentThreadState(const ThreadState& TS) { // Set Current Thread State.
  82. MyThreadState = const_cast<ThreadState*>(&TS);
  83. }
  84. const ThreadState& Thread::CurrentThreadState() { return (*MyThreadState); } // Get Current Thread State.
  85. ThreadStatusRecord Thread::StatusReport() { // Get a status report from this thread.
  86. return
  87. ThreadStatusRecord( // Status record.
  88. this,
  89. const_cast<ThreadType&>(MyThreadType),
  90. *MyThreadState,
  91. RunningFlag,
  92. BadFlag,
  93. BadWhat,
  94. MyThreadName
  95. );
  96. }
  97. // launchTask() calls and monitors myTask for exceptions and set's the correct
  98. // states for the isBad and isRunning flags.
  99. void Thread::launchTask() { // Launch and watch myTask()
  100. try { // Do this safely.
  101. RunningFlag = true; // Now we are running.
  102. CurrentThreadState(ThreadStarted); // Set the running state.
  103. myTask(); // myTask() is called.
  104. } // myTask() should handle exceptions.
  105. catch(const std::exception& e) { // Unhandled exceptions are informative:
  106. BadFlag = true; // They mean the thread went bad but
  107. BadWhat = e.what(); // we have an idea what went wrong.
  108. } // We shouldn't get other kinds of
  109. catch(...) { // exceptions because if things go
  110. BadFlag = true; // wrong and one gets through this
  111. BadWhat = "Unkown Exception(...)"; // is all we can say about it.
  112. }
  113. RunningFlag = false; // When we're done, we're done.
  114. if(BadFlag) CurrentThreadState(ThreadFailed); // If we're bad we failed.
  115. else CurrentThreadState(ThreadStopped); // If we're not bad we stopped.
  116. }
  117. // getMyThread() returns the local thread primative.
  118. thread_primative Thread::getMyThread() { return MyThread; } // Return my thread primative.
  119. // runThreadTask() is a helper function to start threads. It is the function
  120. // that is acutally launched as a new thread. It's whole job is to call the
  121. // myTask() method on the object passed to it as it is launched.
  122. // The run() method creates a new thread with ThreadRunner() as the main
  123. // function, having passed it's object.
  124. // WIN32 and POSIX have different versions of both the main thread function
  125. // and the way to launch it.
  126. #ifdef WIN32
  127. Thread::Thread() : // When constructing a WIN32 thread
  128. MyThreadType(Thread::Type), // Use generic Thread Type.
  129. MyThreadName("UnNamed Thread"), // Use a generic Thread Name.
  130. MyThread(NULL), // Null the thread handle.
  131. RunningFlag(false), // Couldn't be running yet.
  132. BadFlag(false) { // Couldn't be bad yet.
  133. Threads.rememberThread(this); // Remember this thread.
  134. CurrentThreadState(ThreadInitialized); // Set our initialized state.
  135. }
  136. Thread::Thread(const ThreadType& T, const std::string N) : // Construct with specific Type/Name
  137. MyThreadType(T), // Use generic Thread Type.
  138. MyThreadName(N), // Use a generic Thread Name.
  139. MyThread(NULL), // Null the thread handle.
  140. RunningFlag(false), // Couldn't be running yet.
  141. BadFlag(false) { // Couldn't be bad yet.
  142. Threads.rememberThread(this); // Remember this thread.
  143. CurrentThreadState(ThreadInitialized); // Set our initialized state.
  144. }
  145. Thread::~Thread() { // In WIN32 land when we destroy the
  146. if(NULL != MyThread) { // thread object check for a valid
  147. CloseHandle(MyThread); // thread handle and destroy it if
  148. } // it exists.
  149. RunningFlag = false; // The thread is not running.
  150. Threads.forgetThread(this); // Forget this thread.
  151. CurrentThreadState(ThreadDestroyed); // The Thread has left the building.
  152. }
  153. unsigned __stdcall runThreadTask(void* thread_object) { // The WIN32 version has this form.
  154. ((Thread*)thread_object)->launchTask(); // Run the task.
  155. _endthreadex(0); // Signal the thread is finished.
  156. return 0; // Satisfy the unsigned return.
  157. }
  158. void Thread::run() { // Run a WIN32 thread...
  159. unsigned tid; // Thread id to toss. Only need Handle.
  160. MyThread = (HANDLE) _beginthreadex(NULL,0,runThreadTask,this,0,&tid); // Create a thread calling ThreadRunner
  161. if(NULL == MyThread) BadFlag = true; // and test that the resutl was valid.
  162. }
  163. void Thread::join() { // To join in WIN32
  164. WaitForSingleObject(MyThread, INFINITE); // Wait for the thread by handle.
  165. }
  166. #else
  167. Thread::Thread() : // POSIX Thread constructor.
  168. MyThreadType(Thread::Type), // Use a generic Thread Type.
  169. MyThreadName("UnNamed Thread"), // Use a generic Thread Name.
  170. RunningFlag(false), // Can't be running yet.
  171. BadFlag(false) { // Can't be bad yet.
  172. Threads.rememberThread(this); // Remember this thread.
  173. CurrentThreadState(ThreadInitialized); // Set our initialized state.
  174. }
  175. Thread::Thread(const ThreadType& T, const std::string N) : // POSIX Specific Thread Constructor.
  176. MyThreadType(T), // Use a generic Thread Type.
  177. MyThreadName(N), // Use a generic Thread Name.
  178. RunningFlag(false), // Can't be running yet.
  179. BadFlag(false) { // Can't be bad yet.
  180. Threads.rememberThread(this); // Remember this thread.
  181. CurrentThreadState(ThreadInitialized); // Set our initialized state.
  182. }
  183. Thread::~Thread() { // POSIX destructor.
  184. RunningFlag = false; // Not running now for sure.
  185. Threads.forgetThread(this); // Forget this thread.
  186. CurrentThreadState(ThreadDestroyed); // The Thread has left the building.
  187. }
  188. void* runThreadTask(void* thread_object) { // The POSIX version has this form.
  189. ((Thread*)thread_object)->launchTask();
  190. return NULL;
  191. }
  192. void Thread::run() { // Run a POSIX thread...
  193. int result = pthread_create(&MyThread, NULL, runThreadTask, this); // Create a thread calling ThreadRunner
  194. if(0 != result) BadFlag = true; // and test that there was no error.
  195. }
  196. void Thread::join() { // To join in POSIX
  197. pthread_join(MyThread, NULL); // call pthread_join with MyThread.
  198. }
  199. #endif
  200. // End Thread
  201. ////////////////////////////////////////////////////////////////////////////////
  202. ////////////////////////////////////////////////////////////////////////////////
  203. // Mutex
  204. #ifdef WIN32
  205. // WIN32 Mutex Implementation //////////////////////////////////////////////////
  206. // The original design of the WIN32 Mutex used critical sections. However after
  207. // additional research it was determined that the use of a Semaphore with an
  208. // initial count of 1 would work better overall on multiple Winx platforms -
  209. // especially SMP systems.
  210. const RuntimeCheck ThreadingCheck3("Mutex::Mutex():ThreadingCheck3(NULL != MyMutex)");
  211. Mutex::Mutex() : // Creating a WIN32 Mutex means
  212. IAmLocked(false) { // Setting IAmLocked to false and
  213. MyMutex = CreateSemaphore(NULL, 1, 1, NULL); // create a semaphore object with
  214. ThreadingCheck3(NULL != MyMutex); // a count of 1.
  215. }
  216. const ExitCheck ThreadingCheck4("Mutex::~Mutex():");
  217. Mutex::~Mutex() { // Destroying a WIN32 Mutex means
  218. ThreadingCheck4(false == IAmLocked); // Make sure we're not in use and
  219. CloseHandle(MyMutex); // destroy the semaphore object.
  220. }
  221. bool Mutex::tryLock() { // Trying to lock WIN32 Mutex means
  222. bool DoIHaveIt = false; // Start with a pessimistic assumption
  223. if(
  224. false == IAmLocked && // If we have a shot at this and
  225. WAIT_OBJECT_0 == WaitForSingleObject(MyMutex, 0) // we actually get hold of the semaphore
  226. ) { // then we can set our flags...
  227. IAmLocked = true; // Set IAmLocked, because we are and
  228. DoIHaveIt = true; // set our result to true.
  229. }
  230. return DoIHaveIt; // Return true if we got it (see above).
  231. }
  232. const RuntimeCheck ThreadingCheck5("Mutex::lock():ThreadingCheck5(WAIT_OBJECT_0 == WaitForSingleObject(MyMutex, INFINITE))");
  233. void Mutex::lock() { // Locking the WIN32 Mutex means
  234. ThreadingCheck5(WAIT_OBJECT_0 == WaitForSingleObject(MyMutex, INFINITE)); // Wait on the semaphore - only 1 will
  235. IAmLocked = true; // get through or we have a big problem.
  236. }
  237. const LogicCheck ThreadingCheck6("Mutex::unlock():ThreadingCheck6(true == IAmLocked)");
  238. void Mutex::unlock() { // Unlocking the WIN32 Mutex means
  239. ThreadingCheck6(true == IAmLocked); // making sure we're really locked then
  240. IAmLocked = false; // reset the IAmLocked flag and
  241. ReleaseSemaphore(MyMutex, 1, NULL); // release the semaphore.
  242. }
  243. bool Mutex::isLocked() { return IAmLocked; } // Return the IAmLocked flag.
  244. #else
  245. // POSIX Mutex Implementation //////////////////////////////////////////////////
  246. const RuntimeCheck ThreadingCheck7("Mutex::Mutex():ThreadingCheck7(0 == pthread_mutex_init(&MyMutex,NULL))");
  247. Mutex::Mutex() : // Constructing a POSIX mutex means
  248. IAmLocked(false) { // setting the IAmLocked flag to false and
  249. ThreadingCheck7(0 == pthread_mutex_init(&MyMutex,NULL)); // initializing the mutex_t object.
  250. }
  251. const ExitCheck ThreadingCheck8("Mutex::~Mutex():ThreadingCheck8(false == IAmLocked)");
  252. const ExitCheck ThreadingCheck9("Mutex::~Mutex():ThreadingCheck9(0 == pthread_mutex_destroy(&MyMutex))");
  253. Mutex::~Mutex() { // Before we destroy our mutex we check
  254. ThreadingCheck8(false == IAmLocked); // to see that it is not locked and
  255. ThreadingCheck9(0 == pthread_mutex_destroy(&MyMutex)); // destroy the primative.
  256. }
  257. const RuntimeCheck ThreadingCheck10("Mutex::lock():ThreadingCheck10(0 == pthread_mutex_lock(&MyMutex));");
  258. void Mutex::lock() { // Locking a POSIX mutex means
  259. ThreadingCheck10(0 == pthread_mutex_lock(&MyMutex)); // asserting our lock was successful and
  260. IAmLocked = true; // setting the IAmLocked flag.
  261. }
  262. const LogicCheck ThreadingCheck11("Mutex::unlock():ThreadingCheck11(true == IAmLocked)");
  263. const RuntimeCheck ThreadingCheck12("Mutex::unlock():ThreadingCheck12(0 == pthread_mutex_unlock(&MyMutex))");
  264. void Mutex::unlock() { // Unlocking a POSIX mutex means
  265. ThreadingCheck11(true == IAmLocked); // asserting that we are locked,
  266. IAmLocked = false; // clearing the IAmLocked flag, and
  267. ThreadingCheck12(0 == pthread_mutex_unlock(&MyMutex)); // unlocking the actual mutex.
  268. }
  269. bool Mutex::tryLock() { // Trying to lock a POSIX mutex means
  270. bool DoIHaveIt = false; // starting off pessimistically.
  271. if(false == IAmLocked) { // If we are not locked yet then we
  272. if(0 == pthread_mutex_trylock(&MyMutex)) { // try to lock the mutex. If we succeed
  273. IAmLocked = true; // we set our IAmLocked flag and our
  274. DoIHaveIt = true; // DoIHaveIt flag to true;
  275. }
  276. }
  277. return DoIHaveIt; // In any case we return the result.
  278. }
  279. bool Mutex::isLocked() { return IAmLocked; } // Return the IAmLocked flag.
  280. #endif
  281. // End Mutex
  282. ////////////////////////////////////////////////////////////////////////////////
  283. ////////////////////////////////////////////////////////////////////////////////
  284. // ScopeMutex
  285. ScopeMutex::ScopeMutex(Mutex& M) : // When constructing a ScopeMutex,
  286. MyMutex(M) { // Initialize MyMutex with what we are given
  287. MyMutex.lock(); // and then immediately lock it.
  288. }
  289. ScopeMutex::~ScopeMutex() { // When a ScopeMutex is destroyed,
  290. MyMutex.unlock(); // it first unlocks it's mutex.
  291. }
  292. // End ScopeMutex
  293. ////////////////////////////////////////////////////////////////////////////////
  294. ////////////////////////////////////////////////////////////////////////////////
  295. // Production Gateway
  296. #ifdef WIN32
  297. // Win32 Implementation ////////////////////////////////////////////////////////
  298. const RuntimeCheck ThreadingCheck13("ProductionGateway::ProductionGateway():ThreadingCheck13(NULL != MySemaphore)");
  299. ProductionGateway::ProductionGateway() { // Construct in Windows like this:
  300. const int HUGENUMBER = 0x7fffffL; // Work without any real limits.
  301. MySemaphore = CreateSemaphore(NULL, 0, HUGENUMBER, NULL); // Create a Semaphore for signalling.
  302. ThreadingCheck13(NULL != MySemaphore); // That should always work.
  303. }
  304. ProductionGateway::~ProductionGateway() { // Be sure to close it when we're done.
  305. CloseHandle(MySemaphore);
  306. }
  307. void ProductionGateway::produce() { // To produce() in WIN32 we
  308. ReleaseSemaphore(MySemaphore, 1, NULL); // release 1 count into the semaphore.
  309. }
  310. void ProductionGateway::consume() { // To consume() in WIN32 we
  311. WaitForSingleObject(MySemaphore, INFINITE); // wait for a count in the semaphore.
  312. }
  313. #else
  314. // POSIX Implementation ////////////////////////////////////////////////////////
  315. const RuntimeCheck ThreadingCheck14("ProductionGateway::ProductionGateway():ThreadingCheck14(0 == pthread_mutex_init(&MyMutex, NULL));");
  316. const RuntimeCheck ThreadingCheck15("ProductionGateway::ProductionGateway():ThreadingCheck15(0 == pthread_cond_init(&MyConditionVariable, NULL))");
  317. ProductionGateway::ProductionGateway() : // Construct in POSIX like this:
  318. Product(0), // All of our counts start at zero.
  319. Waiting(0),
  320. Signaled(0) {
  321. ThreadingCheck14(0 == pthread_mutex_init(&MyMutex, NULL)); // Initialize our mutex.
  322. ThreadingCheck15(0 == pthread_cond_init(&MyConditionVariable, NULL)); // Initialize our condition variable.
  323. }
  324. const ExitCheck ThreadingCheck16("ProductionGateway::~ProductionGateway():ThreadingCheck16(0 == pthread_mutex_destroy(&MyMutex))");
  325. const ExitCheck ThreadingCheck17("ProductionGateway::~ProductionGateway():ThreadingCheck17(0 == pthread_cond_destroy(&MyConditionVariable))");
  326. ProductionGateway::~ProductionGateway() { // When we're done we must destroy
  327. ThreadingCheck16(0 == pthread_mutex_destroy(&MyMutex)); // our local mutex and
  328. ThreadingCheck17(0 == pthread_cond_destroy(&MyConditionVariable)); // our condition variable.
  329. }
  330. const RuntimeCheck ThreadingCheck18("ProductionGateway::produce():ThreadingCheck18(0 == pthread_mutex_lock(&MyMutex))");
  331. const RuntimeCheck ThreadingCheck19("ProductionGateway::produce():ThreadingCheck19(0 == pthread_cond_signal(&MyConditionVariable))");
  332. const RuntimeCheck ThreadingCheck20("ProductionGateway::produce():ThreadingCheck20(0 == pthread_mutex_unlock(&MyMutex))");
  333. void ProductionGateway::produce() { // To produce in POSIX
  334. ThreadingCheck18(0 == pthread_mutex_lock(&MyMutex)); // Lock our mutex.
  335. ++Product; // Add an item to our product count.
  336. if(Signaled < Waiting) { // If anybody is waiting that has not
  337. ThreadingCheck19(0 == pthread_cond_signal(&MyConditionVariable)); // yet been signaled then signal them
  338. ++Signaled; // and keep track. They will count this
  339. } // down as they awaken.
  340. ThreadingCheck20(0 == pthread_mutex_unlock(&MyMutex)); // At the end unlock our mutex so
  341. } // waiting threads can fly free :-)
  342. const RuntimeCheck ThreadingCheck21("ProductionGateway::consume():ThreadingCheck21(0 == pthread_mutex_lock(&MyMutex))");
  343. const RuntimeCheck ThreadingCheck22("ProductionGateway::consume():ThreadingCheck22(0 == pthread_cond_wait(&MyConditionVariable, &MyMutex))");
  344. const RuntimeCheck ThreadingCheck23("ProductionGateway::consume():ThreadingCheck23(0 == pthread_mutex_unlock(&MyMutex))");
  345. void ProductionGateway::consume() { // To consume in POSIX
  346. ThreadingCheck21(0 == pthread_mutex_lock(&MyMutex)); // Lock our mutex.
  347. while(0 >= Product) { // Until we have something to consume,
  348. ++Waiting; // wait for a signal from
  349. ThreadingCheck22(0 == pthread_cond_wait(&MyConditionVariable, &MyMutex)); // our producer. When we have a signal
  350. --Waiting; // we are done waiting and we have
  351. --Signaled; // been signaled. Of course, somebody
  352. } // may have beaten us to it so check.
  353. --Product; // If we have product then take it.
  354. ThreadingCheck23(0 == pthread_mutex_unlock(&MyMutex)); // At the end unlock our mutex so
  355. }
  356. #endif
  357. // End Production Gateway
  358. ////////////////////////////////////////////////////////////////////////////////
  359. } // End namespace codedweller