KSquare Utilities
KKB::KKThread Class Reference

The base class to be used any thread. More...

#include <KKThread.h>

+ Inheritance diagram for KKB::KKThread:

Public Types

typedef KKThreadKKThreadPtr
 
enum  ThreadPriority : int { ThreadPriority::Null, ThreadPriority::Low, ThreadPriority::Normal, ThreadPriority::High }
 
enum  ThreadStatus : int {
  ThreadStatus::Null, ThreadStatus::NotStarted, ThreadStatus::Starting, ThreadStatus::Running,
  ThreadStatus::Stopping, ThreadStatus::Stopped
}
 

Public Member Functions

 KKThread (const KKStr &_threadName, KKThreadManagerPtr _threadManager, MsgQueuePtr _msgQueue)
 
virtual ~KKThread ()
 
void AddShutdownPrerequistite (KKThreadPtr _thread)
 Specify threads that must stop before this thread is started. More...
 
void AddStartPrerequistite (KKThreadPtr _thread)
 Specify threads that must start before this thread is started. More...
 
VolConstBoolCancelFlag () const
 
bool Crashed () const
 
void Crashed (bool _crashed)
 
const KKStrExceptionText () const
 
void ExceptionText (const KKStr &_exceptionText)
 
KKStrListPtr GetMsgs ()
 
void Kill ()
 stops the running thread and frees the thread handle More...
 
kkint32 MemoryConsumedEstimated ()
 
KKB::MsgQueuePtr MsgQueue ()
 
bool OkToShutdown () const
 
bool OkToStart () const
 
virtual void Run ()
 
VolConstBoolShutdownFlag () const
 
void ShutdownThread ()
 
void Start (ThreadPriority _priority, bool &successful)
 
ThreadStatus Status () const
 
void Status (ThreadStatus _status)
 
const KKStrStatusStr () const
 
VolConstBoolTerminateFlag () const
 
virtual void TerminateFlagChanged ()
 Will be called whenever the value of 'terminateFlag' is changed; derived classes should override this method if they need to be aware that the terminaeFlag has changed. This give them a chance to let other objects/methods know that the flag has changed. More...
 
void TerminateThread ()
 
kkint32 ThreadId () const
 
const KKStrThreadName () const
 
bool ThreadStillProcessing () const
 
void WaitForThreadToStop (kkuint32 maxTimeToWait)
 Called by separate thread; will stay in loop until the thread controlled by this instance shutdown or it waited the 'maxTimeToWait'. More...
 

Static Public Member Functions

static const KKStrThreadStatusToStr (ThreadStatus)
 

Protected Member Functions

void AddMsg (KKStrPtr msg)
 
void AddMsg (const KKStr &msg)
 
bool ShutdownOrTerminateRequested ()
 
bool ThereIsACircularReferenceShutdown (KKThreadPtr _thread) const
 
bool ThereIsACircularReferenceStart (KKThreadPtr _thread) const
 

Detailed Description

The base class to be used any thread.

This will be the base class for each one of the different types of processing.

Definition at line 27 of file KKThread.h.

Member Typedef Documentation

Definition at line 30 of file KKThread.h.

Member Enumeration Documentation

enum KKB::KKThread::ThreadPriority : int
strong
Enumerator
Null 
Low 
Normal 
High 

Definition at line 32 of file KKThread.h.

32  : int
33  {Null,
34  Low,
35  Normal,
36  High
37  };
enum KKB::KKThread::ThreadStatus : int
strong
Enumerator
Null 
NotStarted 
Starting 
Running 
Stopping 
Stopped 

Definition at line 39 of file KKThread.h.

39  : int
40  {Null,
41  NotStarted,
42  Starting,
43  Running,
44  Stopping,
45  Stopped
46  };

Constructor & Destructor Documentation

KKThread::KKThread ( const KKStr _threadName,
KKThreadManagerPtr  _threadManager,
MsgQueuePtr  _msgQueue 
)

Definition at line 83 of file KKThread.cpp.

References KKB::KKStr::KKStr(), Normal, and NotStarted.

Referenced by KKB::KKThreadManager::KKThreadManager().

86  :
87  crashed (false),
88  msgQueue (_msgQueue),
89  priority (ThreadPriority::Normal),
90  shutdownFlag (false),
91  shutdownPrerequisites (NULL),
92  startPrerequisites (NULL),
93  status (ThreadStatus::NotStarted),
94  terminateFlag (false),
95  threadId (0),
96  threadName (_threadName)
97 
98 {
99 #if defined(WIN32)
100  windowsThreadHandle = NULL;
101  windowsThreadId = 0;
102 #else
103  linuxThreadId = 0;
104 #endif
105 }
KKThread::~KKThread ( )
virtual

Definition at line 109 of file KKThread.cpp.

110 {
111  delete shutdownPrerequisites; shutdownPrerequisites = NULL;
112  delete startPrerequisites; startPrerequisites = NULL;
113 }

Member Function Documentation

void KKThread::AddMsg ( KKStrPtr  msg)
protected

Taking ownership of 'msg' and will append to 'msgQueue'.

Definition at line 154 of file KKThread.cpp.

References KKB::MsgQueue::AddMsg().

155 {
156  if (msgQueue == NULL)
157  {
158  cerr << endl
159  << "KKThread::AddMsg ***ERROR*** msgQuue is not defined." << endl
160  << " Msg[" << *msg << "]." << endl
161  << endl;
162  delete msg;
163  msg = NULL;
164  }
165  else
166  {
167  msgQueue->AddMsg (msg);
168  }
169 } /* AddMsg */
void AddMsg(KKStrPtr msg)
Take ownership of &#39;msg&#39; and add to end of the queue.
Definition: MsgQueue.cpp:58
HTMLReport &__cdecl endl(HTMLReport &htmlReport)
Definition: HTMLReport.cpp:240
void KKThread::AddMsg ( const KKStr msg)
protected

A copy of the message 'msg' will be added to the end of msgQueue.

Definition at line 174 of file KKThread.cpp.

References KKB::MsgQueue::AddMsg(), KKB::KKStr::Concat(), KKB::KKStr::KKStr(), KKB::KKStr::Len(), KKB::osGetLocalDateTime(), KKB::osGetThreadId(), and KKB::DateTime::Time().

Referenced by Run().

175 {
176  if (msgQueue == NULL)
177  {
178  cerr << endl
179  << "KKThread::AddMsg ***ERROR*** msgQuue is not defined." << endl
180  << " Msg[" << msg << "]." << endl
181  << endl;
182  }
183  else
184  {
185  KKStr msgTemp (msg.Len () + 20);
186  msgTemp << osGetThreadId () << " - " << osGetLocalDateTime ().Time () << "->" << msg;
187  msgQueue->AddMsg (msgTemp);
188  }
189 } /* AddMsg */
void AddMsg(KKStrPtr msg)
Take ownership of &#39;msg&#39; and add to end of the queue.
Definition: MsgQueue.cpp:58
HTMLReport &__cdecl endl(HTMLReport &htmlReport)
Definition: HTMLReport.cpp:240
KKB::DateTime osGetLocalDateTime()
Returned the current local date and time.
kkint32 osGetThreadId()
kkuint32 Len() const
Returns the number of characters in the string.
Definition: KKStr.h:366
const TimeType & Time() const
Definition: DateTime.h:232
void KKThread::AddShutdownPrerequistite ( KKThreadPtr  _thread)

Specify threads that must stop before this thread is started.

This method can be called multiple times; the information is used by the 'KKTHreadManager' instance to control the orderly shutdown of the controlling 'KKTHreadManager' instance.

Parameters
[in]_threadA thread that needs to be in the 'Stopped' status before this thread can be shutdown; we do NOT take ownership.

Definition at line 510 of file KKThread.cpp.

References KKB::KKThreadList::KKThreadList().

511 {
512  if (!shutdownPrerequisites)
513  shutdownPrerequisites = new KKThreadList (false);
514  shutdownPrerequisites->PushOnBack (_thread);
515 }
virtual void PushOnBack(EntryPtr _entry)
Definition: KKQueue.h:398
void KKThread::AddStartPrerequistite ( KKThreadPtr  _thread)

Specify threads that must start before this thread is started.

This method can be called multiple times; the information is used by the 'KKTHreadManager' instance to control the start of the thread.

Parameters
[in]_threadA thread that needs to be in the 'Running' status before this thread can start; we do NOT take ownership.

Definition at line 501 of file KKThread.cpp.

References KKB::KKThreadList::KKThreadList().

502 {
503  if (!startPrerequisites)
504  startPrerequisites = new KKThreadList (false);
505  startPrerequisites->PushOnBack (_thread);
506 }
virtual void PushOnBack(EntryPtr _entry)
Definition: KKQueue.h:398
VolConstBool& KKB::KKThread::CancelFlag ( ) const
inline

Another name for 'TerminateFlag'.

Definition at line 60 of file KKThread.h.

bool KKB::KKThread::Crashed ( ) const
inline

Signifies that this thread had to terminate on its own because of an abnormal situation; such as a memory corruption.

Definition at line 62 of file KKThread.h.

Referenced by KKB::KKThreadManager::AnyProcessorsCrashed().

void KKB::KKThread::Crashed ( bool  _crashed)
inline

Definition at line 89 of file KKThread.h.

Referenced by KKB::ThreadStartCallBack().

89 {crashed = _crashed;}
const KKStr& KKB::KKThread::ExceptionText ( ) const
inline

If the overloaded 'Run' method of a derived class generates a exception that is not caught; then the ''ThreadStartCallBack' will catch it and store the related text in this field. In this case the 'Crashed()' method will return 'true'.

Definition at line 66 of file KKThread.h.

void KKB::KKThread::ExceptionText ( const KKStr _exceptionText)
inline

Definition at line 90 of file KKThread.h.

References KKB::KKStr::operator=().

Referenced by KKB::ThreadStartCallBack().

90 {exceptionText = _exceptionText;}
KKStrListPtr KKThread::GetMsgs ( )

Definition at line 193 of file KKThread.cpp.

References KKB::MsgQueue::GetNextMsg(), and KKB::KKStrList::KKStrList().

194 {
195  KKStrListPtr results = new KKStrList (true);
196  KKStrPtr msg = msgQueue->GetNextMsg ();
197  while (msg)
198  {
199  results->PushOnBack (msg);
200  msg = msgQueue->GetNextMsg ();
201  }
202 
203  return results;
204 } /* GetMsgs */
KKStrPtr GetNextMsg()
Removes from the queue the oldest message added to the queue that has not been removed.
Definition: MsgQueue.cpp:107
virtual void PushOnBack(EntryPtr _entry)
Definition: KKQueue.h:398
void KKThread::Kill ( )

stops the running thread and frees the thread handle

Definition at line 427 of file KKThread.cpp.

Referenced by KKB::KKThreadManager::KillAllRunningThreads(), and WaitForThreadToStop().

428 {
429  if (windowsThreadHandle == NULL)
430  return;
431 
432  WaitForSingleObject (windowsThreadHandle, INFINITE);
433  CloseHandle (windowsThreadHandle);
434  windowsThreadHandle = NULL;
435 } /* Kill */
kkint32 KKThread::MemoryConsumedEstimated ( )

Definition at line 117 of file KKThread.cpp.

References KKB::MsgQueue::MemoryConsumedEstimated(), KKB::KKThreadList::MemoryConsumedEstimated(), and KKB::KKStr::MemoryConsumedEstimated().

Referenced by KKB::KKThreadList::MemoryConsumedEstimated().

118 {
119  kkint32 estMem = sizeof (crashed) +
120  sizeof (msgQueue) +
121  sizeof (shutdownFlag) +
122  sizeof (startPrerequisites) +
123  sizeof (shutdownPrerequisites) +
124  sizeof (status) +
125  sizeof (terminateFlag) +
126  threadName.MemoryConsumedEstimated ();
127 
128  if (msgQueue)
129  estMem += msgQueue->MemoryConsumedEstimated ();
130 
131  if (startPrerequisites)
132  estMem += startPrerequisites->MemoryConsumedEstimated ();
133 
134  if (shutdownPrerequisites)
135  estMem += shutdownPrerequisites->MemoryConsumedEstimated ();
136 
137  return estMem;
138 }
kkint32 MemoryConsumedEstimated() const
Definition: KKStr.cpp:766
__int32 kkint32
Definition: KKBaseTypes.h:88
kkint32 MemoryConsumedEstimated()
Returns an estimate of the amount of memory consumed in bytes by this instance.
Definition: MsgQueue.cpp:146
kkint32 MemoryConsumedEstimated() const
Definition: KKThread.cpp:575
KKB::MsgQueuePtr KKB::KKThread::MsgQueue ( )
inline

Definition at line 71 of file KKThread.h.

71 {return msgQueue;}
bool KKThread::OkToShutdown ( ) const

Returns 'true' if all shutdown prerequisites are in the 'Stopped' status.

Definition at line 519 of file KKThread.cpp.

References Status(), and Stopped.

Referenced by KKB::KKThreadManager::ShutdownProcessing().

520 {
521  if (!shutdownPrerequisites)
522  return true;
523 
525  for (idx = shutdownPrerequisites->begin (); idx != shutdownPrerequisites->end (); ++idx)
526  {
527  KKThreadPtr preReq = *idx;
528  if (preReq->Status () != ThreadStatus::Stopped)
529  return false;
530  }
531  return true;
532 } /* OkToShutdown */
ThreadStatus Status() const
Definition: KKThread.h:72
std::vector< KKThread * >::const_iterator const_iterator
Definition: KKQueue.h:89
The base class to be used any thread.
Definition: KKThread.h:27
bool KKThread::OkToStart ( ) const

Returns 'true' if all start prerequisites are in the 'Running' status.

Definition at line 536 of file KKThread.cpp.

References Running, and Status().

537 {
538  if (!startPrerequisites)
539  return true;
540 
542  for (idx = startPrerequisites->begin (); idx != startPrerequisites->end (); ++idx)
543  {
544  KKThreadPtr preReq = *idx;
545  if (preReq->Status () != ThreadStatus::Running)
546  return false;
547  }
548  return true;
549 } /* OkToStart */
ThreadStatus Status() const
Definition: KKThread.h:72
std::vector< KKThread * >::const_iterator const_iterator
Definition: KKQueue.h:89
The base class to be used any thread.
Definition: KKThread.h:27
void KKThread::Run ( )
virtual

Reimplemented in KKB::KKThreadManager.

Definition at line 447 of file KKThread.cpp.

References AddMsg().

Referenced by KKB::ThreadStartCallBack().

448 {
449  // This method should have been over ridden by a derived class.
450  const char* msg = "KKThread::Run ***ERROR*** This method should have been over ridden by a derived class.";
451 
452  cerr << endl << endl << msg << endl
453  << endl;
454  AddMsg (msg);
455 }
HTMLReport &__cdecl endl(HTMLReport &htmlReport)
Definition: HTMLReport.cpp:240
void AddMsg(KKStrPtr msg)
Definition: KKThread.cpp:154
VolConstBool& KKB::KKThread::ShutdownFlag ( ) const
inline

Indicates that the application wants this thread to complete what work is queued up for it top process. Threads need to monitor this flag; if it goes true they are to complete all processing that is queued up and then shutdown. This is

Definition at line 75 of file KKThread.h.

Referenced by KKB::KKThreadManager::ShutdownProcessing().

bool KKB::KKThread::ShutdownOrTerminateRequested ( )
inlineprotected

Definition at line 148 of file KKThread.h.

148 {return (terminateFlag || shutdownFlag);}
void KKThread::ShutdownThread ( )

Call this method to have its thread finish what ever is in the queue and then exit.

Definition at line 231 of file KKThread.cpp.

Referenced by KKB::KKThreadManager::ShutdownProcessing().

232 {
233  shutdownFlag = true;
234 }
void KKThread::Start ( ThreadPriority  _priority,
bool &  successful 
)

Call this method to start thread; it will call the method "Run".

Definition at line 352 of file KKThread.cpp.

References KKB::KKException::KKException().

355 {
356  priority = _priority;
357 
358  windowsThreadHandle = (unsigned long*)CreateThread (NULL,
359  0,
360  (LPTHREAD_START_ROUTINE)ThreadStartCallBack,
361  (KKThreadPtr)this,
362  0,
363  &windowsThreadId
364  );
365  if (windowsThreadHandle == NULL)
366  {
367  successful = false;
368  throw KKException ("Failed to create thread");
369  }
370  else
371  {
372  threadId = (kkint32)windowsThreadId;
373 
374  switch (priority)
375  {
378  SetThreadPriority (windowsThreadHandle, THREAD_PRIORITY_BELOW_NORMAL);
379  break;
380 
381  case ThreadPriority::Low:
382  SetThreadPriority (windowsThreadHandle, THREAD_PRIORITY_NORMAL);
383  break;
384 
386  SetThreadPriority (windowsThreadHandle, THREAD_PRIORITY_ABOVE_NORMAL);
387  break;
388  }
389  SetThreadName ();
390  successful = true;
391  }
392 } /* Start */
__int32 kkint32
Definition: KKBaseTypes.h:88
KKThread * KKThreadPtr
Definition: KKThread.h:30
unsigned int ThreadStartCallBack(void *param)
Definition: KKThread.cpp:280
ThreadStatus KKB::KKThread::Status ( ) const
inline
void KKB::KKThread::Status ( ThreadStatus  _status)
inline

Definition at line 91 of file KKThread.h.

Referenced by KKB::ThreadStartCallBack().

91 {status = _status;}
const KKStr& KKB::KKThread::StatusStr ( ) const
inline

Definition at line 73 of file KKThread.h.

References ThreadStatusToStr().

73 {return ThreadStatusToStr (status);}
static const KKStr & ThreadStatusToStr(ThreadStatus)
Definition: KKThread.cpp:144
VolConstBool& KKB::KKThread::TerminateFlag ( ) const
inline

Indicates that thread is to stop processing ASAP, release any resources it holds and terminate. Threads need to monitor this flag; if it goes 'true' they need to terminate ASAP releasing all allocated resources. Typically set to true when user request to cancel processing.

Definition at line 80 of file KKThread.h.

void KKThread::TerminateFlagChanged ( )
virtual

Will be called whenever the value of 'terminateFlag' is changed; derived classes should override this method if they need to be aware that the terminaeFlag has changed. This give them a chance to let other objects/methods know that the flag has changed.

Definition at line 216 of file KKThread.cpp.

Referenced by TerminateThread().

217 {
218 }
void KKThread::TerminateThread ( )

Call this method to have its thread stop right away and exit.

Definition at line 208 of file KKThread.cpp.

References TerminateFlagChanged().

Referenced by KKB::KKThreadManager::TerminateProcessing().

209 {
210  terminateFlag = true;
212 }
virtual void TerminateFlagChanged()
Will be called whenever the value of &#39;terminateFlag&#39; is changed; derived classes should override this...
Definition: KKThread.cpp:216
bool KKThread::ThereIsACircularReferenceShutdown ( KKThreadPtr  _thread) const
protected

Definition at line 480 of file KKThread.cpp.

References ThereIsACircularReferenceStart().

481 {
482  if (!shutdownPrerequisites)
483  return false;
484 
486  for (idx = shutdownPrerequisites->begin (); idx != shutdownPrerequisites->end (); ++idx)
487  {
488  KKThreadPtr preReq = *idx;
489  if (preReq == _thread)
490  return true;
491 
492  else if (preReq->ThereIsACircularReferenceStart (_thread))
493  return true;
494  }
495  return false;
496 } /* ThereIsACircularReferenceShutdown */
std::vector< KKThread * >::const_iterator const_iterator
Definition: KKQueue.h:89
The base class to be used any thread.
Definition: KKThread.h:27
bool ThereIsACircularReferenceStart(KKThreadPtr _thread) const
Definition: KKThread.cpp:459
bool KKThread::ThereIsACircularReferenceStart ( KKThreadPtr  _thread) const
protected

Definition at line 459 of file KKThread.cpp.

References ThereIsACircularReferenceStart().

Referenced by ThereIsACircularReferenceShutdown(), and ThereIsACircularReferenceStart().

460 {
461  if (!startPrerequisites)
462  return false;
463 
465  for (idx = startPrerequisites->begin (); idx != startPrerequisites->end (); ++idx)
466  {
467  KKThreadPtr preReq = *idx;
468  if (preReq == _thread)
469  return true;
470 
471  else if (preReq->ThereIsACircularReferenceStart (_thread))
472  return true;
473  }
474  return false;
475 } /* ThereIsACircularReferenceStart */
std::vector< KKThread * >::const_iterator const_iterator
Definition: KKQueue.h:89
The base class to be used any thread.
Definition: KKThread.h:27
bool ThereIsACircularReferenceStart(KKThreadPtr _thread) const
Definition: KKThread.cpp:459
kkint32 KKB::KKThread::ThreadId ( ) const
inline

Definition at line 86 of file KKThread.h.

86 {return threadId;}
const KKStr& KKB::KKThread::ThreadName ( ) const
inline

Definition at line 87 of file KKThread.h.

87 {return threadName;}
const KKStr & KKThread::ThreadStatusToStr ( ThreadStatus  ts)
static

Definition at line 144 of file KKThread.cpp.

References KKB::KKStr::Concat(), KKB::KKStr::EmptyStr(), Null, and Stopped.

Referenced by StatusStr().

145 {
146  if ((ts < ThreadStatus::Null) || (ts > ThreadStatus::Stopped))
147  return KKStr::EmptyStr ();
148  else
149  return threadStatusDescs[(int)ts];
150 }
static const KKStr & EmptyStr()
Static method that returns an Empty String.
Definition: KKStr.cpp:3453
bool KKThread::ThreadStillProcessing ( ) const

Definition at line 221 of file KKThread.cpp.

References Running, Starting, and Stopping.

void KKThread::WaitForThreadToStop ( kkuint32  maxTimeToWait)

Called by separate thread; will stay in loop until the thread controlled by this instance shutdown or it waited the 'maxTimeToWait'.

Does not call the 'ShutdownThread' or 'TerminateThread' methods.

Parameters
[in]maxTimeToWaitWill wait 'maxTimeToWait' seconds before giving up on waiting at which point will try to kill thread.

Definition at line 238 of file KKThread.cpp.

References Kill(), NotStarted, Null, KKB::osGetLocalDateTime(), KKB::osSleepMiliSecs(), Running, KKB::DateTime::Seconds(), Stopped, and Stopping.

239 {
240  if ((status == ThreadStatus::NotStarted) ||
241  (status == ThreadStatus::Stopped) ||
242  (status == ThreadStatus::Null)
243  )
244  {
245  // Thread is not running; we can return.
246  return;
247  }
248 
249  kkuint64 startTime = KKB::osGetLocalDateTime ().Seconds ();
250  kkuint32 timeWaitedSoFar = 0;
251  while ((status == ThreadStatus::Running) || (status == ThreadStatus::Stopping))
252  {
253  osSleepMiliSecs (50);
254  if (maxTimeToWait > 0)
255  {
256  kkuint64 now = osGetLocalDateTime ().Seconds ();
257  timeWaitedSoFar = (kkuint32)(now - startTime);
258  if (timeWaitedSoFar > maxTimeToWait)
259  break;
260  }
261  }
262 
263 
264  if ((status != ThreadStatus::NotStarted) &&
265  (status != ThreadStatus::Stopped) &&
266  (status != ThreadStatus::Null)
267  )
268  {
269  Kill ();
270  }
271 
272 } /* WaitForThreadToStop */
KKB::DateTime osGetLocalDateTime()
Returned the current local date and time.
unsigned __int32 kkuint32
Definition: KKBaseTypes.h:89
void osSleepMiliSecs(kkuint32 numMiliSecs)
unsigned __int64 kkuint64
Definition: KKBaseTypes.h:91
kkuint64 Seconds() const
Definition: DateTime.cpp:1092
void Kill()
stops the running thread and frees the thread handle
Definition: KKThread.cpp:427

The documentation for this class was generated from the following files: