Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

threading.hpp 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. // threading.hpp
  2. //
  3. // (C) 2006 - 2009 MicroNeil Research Corporation.
  4. //
  5. // This program is part of the MicroNeil Research Open Library Project. For
  6. // more information go to http://www.microneil.com/OpenLibrary/index.html
  7. //
  8. // This program is free software; you can redistribute it and/or modify it
  9. // under the terms of the GNU General Public License as published by the
  10. // Free Software Foundation; either version 2 of the License, or (at your
  11. // option) any later version.
  12. //
  13. // This program is distributed in the hope that it will be useful, but WITHOUT
  14. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  15. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  16. // more details.
  17. //
  18. // You should have received a copy of the GNU General Public License along with
  19. // this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  20. // Place, Suite 330, Boston, MA 02111-1307 USA
  21. // The "Threading" module is a basic, cross-platform, multi-threading tool kit.
  22. // The differences between posix compatible systems and win32 based systems are
  23. // abstracted. On win32 systems, native win32 primatives are used to construct.
  24. // efficient, lightweight objects.
  25. // On others we assume we can use pthreads. In either case the objects we have
  26. // here are designed to cover all of the basics efficiently while hiding the
  27. // required under-cover work.
  28. // A lot of this module is coded here in the header with the inline keyword
  29. // because it is likely that the more basic objects can be efficiently compiled
  30. // as inline abstractions to native calls. Really basic systems won't need
  31. // anything beyond what is in this file.
  32. // 20070202.1601 _M Further research has suggested that using a Semaphore in
  33. // WIN32 environments in place of a CRITICAL_SECTION may provide the best
  34. // performance and stability on all platforms. Specifically, SMP platforms may
  35. // race and waste resources with CRITICAL_SECTIONs and in those cases it is
  36. // recommended that the CRITICAL_SECTIONs may be "throttled" using Semaphores
  37. // to limit the number of threads that may contend for a critical section. It
  38. // is also suggested that if the Semaphore has an initialization value of 1
  39. // the CRITICAL_SECTION is redundant. So this code has been modified to do
  40. // precisely that!
  41. //
  42. // This new version also includes a ProductionGateway object that simplifies
  43. // the producer/consumer model. The object keeps track of the number of calls
  44. // to produce() and consume() and ensures that threads will block on consume()
  45. // until a sufficient number of calls to produce() are made. That is, for every
  46. // one call to produce(), a call to consume() will be allowed to proceed. The
  47. // object also allows for the potentially asynchronous nature of these calls.
  48. // 20070530.1751 _M Added top level exception handling in threads along with
  49. // isRunning() and isBad() methods.
  50. // 20060528.1647 _M All of the basics are complete and tested on both WIN32 and
  51. // RHEL4 single and multiple processors.
  52. // Include MNR_threading Once Only =============================================
  53. #pragma once
  54. #include <set>
  55. #include <vector>
  56. #include <string>
  57. #include <queue>
  58. #include "faults.hpp"
  59. namespace codedweller {
  60. class ThreadManager; // ThreadManager does exist.
  61. extern ThreadManager Threads; // Master thread manager.
  62. ////////////////////////////////////////////////////////////////////////////////
  63. // Thread Status & Type
  64. //
  65. // ThreadState objects are constant static objects defined for each Thread class
  66. // so that the thread can update it's state by changing a pointer. The state
  67. // can then be compared between threads of the same type and can be read-out
  68. // as text for debugging purposes.
  69. class ThreadState { // Thread State Object.
  70. public:
  71. const std::string Name; // Text name of thread descriptor.
  72. ThreadState(std::string N) : Name(N) {} // Constructor requires text name.
  73. };
  74. // ThreadType objects are constant static objects defined for each Thread class
  75. // so that classes can be identified by type using a pointer to the constant.
  76. class ThreadType {
  77. public:
  78. const std::string Name;
  79. ThreadType(std::string N) : Name(N) {}
  80. };
  81. class Thread; // There is such thing as a Thread.
  82. class ThreadStatusRecord { // Describes a Thread's condition.
  83. private:
  84. Thread* Pointer; // A pointer to the thread.
  85. ThreadType* Type; // A descriptor of it's type.
  86. ThreadState* State; // A descriptor of it's state.
  87. std::string Name; // Name of the thread if any.
  88. bool isRunning; // True if the thread is running.
  89. bool isBad; // True if the thread is bad.
  90. std::string Fault; // Bad Thread's Fault if any.
  91. public:
  92. ThreadStatusRecord( // Initialize all items.
  93. Thread* P,
  94. ThreadType& T,
  95. ThreadState& S,
  96. bool R,
  97. bool B,
  98. std::string F,
  99. std::string N
  100. ) :
  101. Pointer(P),
  102. Type(&T),
  103. State(&S),
  104. Name(N),
  105. isRunning(R),
  106. isBad(B),
  107. Fault(F)
  108. {}
  109. ThreadStatusRecord& operator=(const ThreadStatusRecord& Right) { // Minimal Assignment Operator
  110. Pointer = Right.Pointer;
  111. Type = Right.Type;
  112. State = Right.State;
  113. isRunning = Right.isRunning;
  114. isBad = Right.isBad;
  115. Fault = Right.Fault;
  116. Name = Right.Name;
  117. return *this;
  118. }
  119. bool operator<(const ThreadStatusRecord& Right) { // Minimal Comparison Operator.
  120. return (Pointer < Right.Pointer);
  121. }
  122. // How to get the details of the report.
  123. const Thread* getPointer() { return Pointer; }
  124. const ThreadType& getType() { return *Type; }
  125. const ThreadState& getState() { return *State; }
  126. bool getRunning() { return isRunning; }
  127. bool getBad() { return isBad; }
  128. std::string getFault() { return Fault; }
  129. std::string getName() { return Name; }
  130. };
  131. typedef std::vector<ThreadStatusRecord> ThreadStatusReport; // Status report type.
  132. // End ThreadDescriptor
  133. ////////////////////////////////////////////////////////////////////////////////
  134. } // End namespace codedweller
  135. ////////////////////////////////////////////////////////////////////////////////
  136. // Win32 / POSIX abstractions
  137. #ifdef WIN32
  138. // When in WIN32 land...
  139. // Remember to compile (on GNU anyway) with -mthreads
  140. #include <windows.h>
  141. #include <process.h>
  142. namespace codedweller {
  143. typedef HANDLE thread_primative; // The WIN32 thread primative abstracts
  144. // HANDLE
  145. typedef HANDLE mutex_primative; // The WIN32 mutex primative abstracts
  146. // a HANDLE to a Semaphore.
  147. inline void threading_yield() { // When we want to yield time in WIN32
  148. SwitchToThread(); // we call SwitchToThread();
  149. }
  150. } // End namespace codedweller
  151. #else
  152. // When in POSIX land...
  153. // Remember to compile (on GMU anyway) with -pthread
  154. #include <pthread.h>
  155. #include <sched.h>
  156. namespace codedweller {
  157. typedef pthread_t thread_primative; // The POSIX thread primative abstracts
  158. // pthread_t
  159. typedef pthread_mutex_t mutex_primative; // The POSIX mutex primative abstracts
  160. // pthread_mutex_t
  161. inline void threading_yield() { // When we want to yield time in POSIX
  162. sched_yield(); // we call sched_yield();
  163. }
  164. } // End namespace codedweller
  165. #endif
  166. // End Win32 / POSIX abstractions
  167. ////////////////////////////////////////////////////////////////////////////////
  168. namespace codedweller {
  169. ////////////////////////////////////////////////////////////////////////////////
  170. // The Thread class gets extended to do any specific work. The pure virtual
  171. // function MyTask is overloaded by the derived class to define that work. It
  172. // is expected that the class will be initialized with any parameters that
  173. // will be used by the thread and that the thread will make available any
  174. // results through public interfaces either during and/or after the thread
  175. // has finished running.
  176. class Thread {
  177. private:
  178. ThreadState* MyThreadState; // Track current thread state.
  179. protected:
  180. const ThreadType& MyThreadType; // Identify thread type.
  181. const std::string MyThreadName; // Name string of this instance.
  182. thread_primative MyThread; // Abstracted thread.
  183. bool RunningFlag; // True when thread is in myTask()
  184. bool BadFlag; // True when myTask() throws!
  185. std::string BadWhat; // Bad exception what() if any.
  186. void CurrentThreadState(const ThreadState& TS); // Set thread state.
  187. public:
  188. Thread(); // Constructor (just in case)
  189. Thread(const ThreadType& T, std::string N); // Construct with specific Type/Name
  190. virtual ~Thread(); // Destructor (just in case)
  191. void run(); // Method to launch this thread.
  192. void join(); // Method to Join this thread.
  193. void launchTask(); // Launch and watch myTask().
  194. virtual void myTask() = 0; // The actual task must be overloaded.
  195. thread_primative getMyThread(); // Inspect my thread primative.
  196. bool isRunning(); // Return the Running flag state.
  197. bool isBad(); // Return the Bad flag state.
  198. const std::string MyFault(); // Return exception Bad fault if any.
  199. const std::string MyName(); // The thread's name.
  200. const ThreadType& MyType(); // Thread type for this thread.
  201. const ThreadState& MyState(); // Returns the current thread state.
  202. const ThreadState& CurrentThreadState(); // Returns the current thread state.
  203. ThreadStatusRecord StatusReport(); // Return's the thread's status reprt.
  204. // Constants for Thread...
  205. const static ThreadType Type; // The thread's type.
  206. const static ThreadState ThreadInitialized; // Constructed successfully.
  207. const static ThreadState ThreadStarted; // Started.
  208. const static ThreadState ThreadFailed; // Failed by unhandled exception.
  209. const static ThreadState ThreadStopped; // Stopped normally.
  210. const static ThreadState ThreadDestroyed; // Safety value for destructed Threads.
  211. };
  212. // End Thread
  213. ////////////////////////////////////////////////////////////////////////////////
  214. ////////////////////////////////////////////////////////////////////////////////
  215. // The Mutex class abstracts a lightweight, very basic mutex object.
  216. // As with the Thread object, more ellaborate forms can be built up from
  217. // this basic mechanism. An important design constraint for this basic
  218. // mutex object is that it work even if the thread that's running was not
  219. // created with the Thread object... that ensures that it can be used in
  220. // code that is destined to function in other applications.
  221. class Mutex {
  222. private:
  223. mutex_primative MyMutex; // Here is our primative mutex.
  224. volatile bool IAmLocked; // Here is our Lock Count.
  225. public:
  226. Mutex(); // Construct the mutex.
  227. ~Mutex(); // Destroy the mutex.
  228. void lock(); // Lock it.
  229. void unlock(); // Unlock it.
  230. bool tryLock(); // Try to lock it.
  231. bool isLocked(); // Check to see if it's locked.
  232. };
  233. // End of Mutex
  234. ////////////////////////////////////////////////////////////////////////////////
  235. ////////////////////////////////////////////////////////////////////////////////
  236. // ScopeMutex
  237. // A ScopeMutex is a nifty trick for locking a mutex during some segment of
  238. // code. On construction, it locks the Mutex that it is given and keeps it
  239. // locked until it is destroyed. Of course this also means that it will unlock
  240. // the mutex when it goes out of scope - which is precisely the point :-)
  241. //
  242. // The right way to use a ScopeMutex is to create it just before you need to
  243. // have control and then forget about it. From a design perspective, you might
  244. // want to make sure that whatever happens after the ScopeMutex has been
  245. // created is as short as possible and if it is not then you may want to
  246. // use the Mutex directly.
  247. //
  248. // The best place to use a ScopeMutex is where you might leave the controling
  249. // bit of code through a number of logical paths such as a logic tree or even
  250. // due to some exceptions. In this context it saves you having to track down
  251. // all of the possible cases and unlock the mutex in each of them.
  252. class ScopeMutex {
  253. private:
  254. Mutex& MyMutex; // ScopeMutex has an ordinary Mutex to use.
  255. public:
  256. ScopeMutex(Mutex& M); // Constructing a ScopeMutex requires a Mutex
  257. ~ScopeMutex(); // We do have special code for descrution.
  258. };
  259. // End ScopeMutex
  260. ////////////////////////////////////////////////////////////////////////////////
  261. ////////////////////////////////////////////////////////////////////////////////
  262. // ProductionGateway
  263. // A ProductionGateway encapsulates the thread synchronization required for a
  264. // producer / consumer relationship. For each call to the produce() method one
  265. // call to the consume() method can proceed. The object takes into account that
  266. // these methods may be called out of sequence and that, for example, produce()
  267. // might be called several times before any calls to consume.
  268. #ifdef WIN32
  269. // Win32 Implementation ////////////////////////////////////////////////////////
  270. class ProductionGateway {
  271. private:
  272. HANDLE MySemaphore; // WIN32 makes this one easy w/ a 0 semi.
  273. public:
  274. ProductionGateway(); // The constructor and destructor handle
  275. ~ProductionGateway(); // creating and destroying the semi.
  276. void produce(); // Produce "releases" the semi.
  277. void consume(); // Consume "waits" if needed.
  278. };
  279. #else
  280. // POSIX Implementation ////////////////////////////////////////////////////////
  281. class ProductionGateway { // Posix needs a few pieces for this.
  282. private:
  283. mutex_primative MyMutex; // Mutex to protect the data.
  284. pthread_cond_t MyConditionVariable; // A condition variable for signaling.
  285. int Product; // A count of unused calls to produce()
  286. int Waiting; // A count of waiting threads.
  287. int Signaled; // A count of signaled threads.
  288. public:
  289. ProductionGateway(); // The constructor and destructor handle
  290. ~ProductionGateway(); // creating and destroying the semi.
  291. void produce(); // Produce "releases" the semi.
  292. void consume(); // Consume "waits" if needed.
  293. };
  294. #endif
  295. // End ProductionGateway
  296. ////////////////////////////////////////////////////////////////////////////////
  297. ////////////////////////////////////////////////////////////////////////////////
  298. // The ThreadManager class provides a global thread management tool. All Thread
  299. // objects register themselves with the Threads object upon construction and
  300. // remove themselves from the registry upon destruction. The Threads object can
  301. // produce a status report for all of the known threads on the system and can
  302. // temporarily lock the existing thread so that it can be contacted reliably.
  303. // locking and unlocking the ThreadManager is intended only for short messages
  304. // that set flags in the thread or pass some small data packet. The lock only
  305. // prevents the thread from being destroyed before the message can be sent so
  306. // that the thread that owns the threadlock will not make any calls to a dead
  307. // pointer. Most apps should be designed so that the threadlock mechanism is
  308. // not required.
  309. class ThreadManager { // Central manager for threads.
  310. friend class Thread; // Threads are friends.
  311. private:
  312. Mutex MyMutex; // Protect our data with this.
  313. std::set<Thread*> KnownThreads; // Keep track of all threads.
  314. void rememberThread(Thread* T); // Threads register themselves.
  315. void forgetThread(Thread* T); // Threads remove themselves.
  316. Thread* LockedThread; // Pointer to locked thread if any.
  317. public:
  318. ThreadManager():LockedThread(0){} // Initialize nice and clean.
  319. ThreadStatusReport StatusReport(); // Get a status report.
  320. bool lockExistingThread(Thread* T); // Locks ThreadManager if T exists.
  321. void unlockExistingThread(Thread* T); // Unlocks ThreadManager if T locked.
  322. };
  323. class ScopeThreadLock { // This is like a ScopeMutex for
  324. private: // the ThreadManager.
  325. Thread* MyLockedThread; // It needs to know it's Thread.
  326. public:
  327. ScopeThreadLock(Thread* T); // Locks T in ThreadManager if it can.
  328. ~ScopeThreadLock(); // Unlocks T in ThreadManager if locked.
  329. bool isGood(); // True if T was locked.
  330. bool isBad(); // False if T was not locked.
  331. };
  332. // End Thread Manager
  333. ////////////////////////////////////////////////////////////////////////////////
  334. ////////////////////////////////////////////////////////////////////////////////
  335. // A ProductionQueue is a templated, thread safe mechanism for implementing
  336. // a producer/consumer relationship. The objects in the queue should be simple
  337. // data so that they can be created, destroyed, and copied without trouble. Put
  338. // another way - the objects in the ProductionQueue should be lightweight
  339. // handles for other things. Those things should be created and destroyed
  340. // elsewhere.
  341. template<typename T> // Templatized
  342. class ProductionQueue { // Production Queue Class
  343. private:
  344. Mutex myMutex; // Contains a mutex and
  345. volatile unsigned int LatestSize; // a volatile (blinking light) size
  346. ProductionGateway myGateway; // integrated with a production
  347. std::queue<T> myQueue; // gateway and a queue.
  348. public:
  349. ProductionQueue() : LatestSize(0) {} // The size always starts at zero.
  350. T take() { // To consume a queued object
  351. myGateway.consume(); // we wait on the production gateway
  352. ScopeMutex OneAtATimePlease(myMutex); // and when we get through we lock
  353. T O = myQueue.front(); // the mutext, take the object on the
  354. myQueue.pop(); // front of the queue, pop it out,
  355. LatestSize = myQueue.size(); // and rest our size (blinking light).
  356. return O; // Then return the object we got.
  357. }
  358. void give(T O) { // To produce a queued object
  359. ScopeMutex OneAtATimePlease(myMutex); // we wait on the mutex. When we
  360. myQueue.push(O); // get through we push our object
  361. LatestSize = myQueue.size(); // into the queue, reset our size
  362. myGateway.produce(); // indicator and tell the gateway.
  363. } // When we're done it can be grabbed.
  364. unsigned int size() { // To check the size we look at
  365. return LatestSize; // the blinking light.
  366. }
  367. };
  368. // End Production Queue
  369. ////////////////////////////////////////////////////////////////////////////////
  370. } // End namespace codedweller