Autowiring  1.0.3
A C++ Inversion of Control Framework
BasicThread Class Referenceabstract

An abstract class for creating a thread with a single Run method. More...

#include <BasicThread.h>

Inheritance diagram for BasicThread:
ContextMember CoreRunnable CoreThread

Public Member Functions

 BasicThread (const char *pName=nullptr)
 
template<class Fx >
void AddTeardownListener (Fx &&listener)
 Adds a function object which will be called when this BasicThread stops running or is destroyed More...
 
std::chrono::steady_clock::time_point GetCreationTime (void)
 The thread creation time. More...
 
std::shared_ptr< void > GetThread (void) const
 
ThreadPriority GetThreadPriority (void) const
 
void GetThreadTimes (std::chrono::milliseconds &kernelTime, std::chrono::milliseconds &userTime)
 Reports kernel and user mode running times for this thread. More...
 
bool IsCompleted (void) const
 
virtual void OnStop (void)
 Invoked by the base class Stop() method. Implement this method to perform any needed cleanup. More...
 
virtual void Run ()=0
 Begins thread execution. More...
 
- Public Member Functions inherited from ContextMember
std::shared_ptr< CoreContextGetContext (void) const
 Retrieves the context associated with this object. More...
 
template<class T >
std::shared_ptr< const T > GetSelf (void) const
 Returns a shared pointer that refers to ourselves More...
 
template<class T >
std::shared_ptr< T > GetSelf (void)
 Returns a shared pointer that refers to ourselves More...
 
virtual void NotifyContextTeardown (void)
 Invoked by the parent context when the parent context is about to be destroyed More...
 
- Public Member Functions inherited from CoreRunnable
virtual bool IsRunning (void) const
 Reports whether this runnable is currently running.
 
bool ShouldStop (void) volatile const
 Reports whether this runnable should stop.
 
virtual bool Start (std::shared_ptr< CoreObject > outstanding)
 Causes this runnable to begin processing. More...
 
void Stop (bool graceful=true)
 Stops this runnable. More...
 
bool ThreadSleep (std::chrono::nanoseconds timeout)
 Sleeps this thread for the specified duration. More...
 
void Wait (void)
 Waits indefinitely. Returns when this runnable stops. More...
 
bool WaitFor (std::chrono::nanoseconds timeout)
 Waits for the specified amount of time. More...
 
template<typename TimeType >
bool WaitUntil (TimeType timepoint)
 Waits until the specified time. More...
 
bool WasStarted (void) volatile const
 Reports whether this runnable was ever started.
 

Static Public Member Functions

static void ForceCoreThreadReidentify (void)
 Forces all Autowiring threads to reidentify themselves. More...
 
static bool IsMainThread (void)
 

Protected Member Functions

void DoAdditionalWait (void) override
 Untimed variant of DoAdditionalWait More...
 
bool DoAdditionalWait (std::chrono::nanoseconds timeout) override
 Invoked just before control is returned to the user. More...
 
virtual void DoRun (std::shared_ptr< CoreObject > &&refTracker)
 Routine that sets up the necessary extranea before a call to Run More...
 
virtual void DoRunLoopCleanup (std::shared_ptr< CoreContext > &&ctxt, std::shared_ptr< CoreObject > &&refTracker)
 Performs all cleanup operations that must take place after DoRun() More...
 
std::mutex & GetLock (void) const
 Recovers a general lock used to synchronize entities in this thread internally. More...
 
bool OnStart () override
 Causes a new thread to be created in which the Run method will be invoked More...
 
void OnStop (bool graceful) override
 Invoked by the base class Stop() method. Override this method to perform any needed cleanup. More...
 
void PerformStatusUpdate (const std::function< void()> &fn) const
 Obtains a mutex, invokes the specified lambda function, and then updates the basic thread's state condition. More...
 
void SetCurrentThreadName (void) const
 Assigns a name to the thread, displayed in debuggers. More...
 
void SetThreadPriority (ThreadPriority threadPriority)
 Sets the thread priority of this thread More...
 
void WaitForStateUpdate (const std::function< bool()> &fn) const
 Waits until the specified lambda function returns true or the thread shuts down. More...
 
- Protected Member Functions inherited from CoreRunnable
const std::shared_ptr< CoreObject > & GetOutstanding (void) const
 

Detailed Description

An abstract class for creating a thread with a single Run method.

This is an abstract class that has a single Run() method for implementation by derived classes. A BasicThread instance remains in the context as long as the thread is running, even if there are no other references to it.

To create a thread, extend BasicThread and implement the desired Run() method. To start the thread, wire your thread object to a context and Initiate() the context. When the SignalShutown() or SignalTermination() methods of the owning context are called, or you call the BasicThread::OnStop() function, the ShouldStop() function will evaluate to true. It is your Run() implementation's responsibility to terminate when ShouldStop() becomes true.

The following example prints out the sequence of prime numbers until the context signals that threads should shutdown:

class PrimeGenerator : public BasicThread {
public:
void Run() override {
unsigned long int test = 2;
while (!ShouldStop())
{
for (unsigned long int i = test/2; i > 0 ; --i) {
if (i == 1) {
std::cout << "Prime: " << test << std::endl;
}
if (test % i == 0) {break;}
}
test++;
}
}
};
CurrentContextPusher pusher(ctxt);
ctxt->Initiate();
ctxt->Wait(std::chrono::milliseconds(100));
ctxt->SignalShutdown(true);
Examples:
ThreadExample.cpp.

Constructor & Destructor Documentation

BasicThread::BasicThread ( const char *  pName = nullptr)

Creates a BasicThread object.

Parameters
pNameAn optional name for this thread. The name is visible in some debuggers.

Member Function Documentation

template<class Fx >
void BasicThread::AddTeardownListener ( Fx &&  listener)
inline

Adds a function object which will be called when this BasicThread stops running or is destroyed

The listener is invoked before the destruction of this BasicThread and also immediately after the BasicThread instance has transitioned to the Stopped state.

Users who attach a teardown listener MUST NOT attempt to invoke any methods not defined by BasicThread, and MUST NOT attempt to invoke any non-final virtual functions available here. The object itself may be partially destroyed by the time the listener is invoked, and virtual methods may not have the expected behavior.

It is guaranteed to be safe to call any non-virtual method defined by BasicThread from a teardown listener.

void BasicThread::DoAdditionalWait ( void  )
overrideprotectedvirtual

Untimed variant of DoAdditionalWait

Reimplemented from CoreRunnable.

bool BasicThread::DoAdditionalWait ( std::chrono::nanoseconds  timeout)
overrideprotectedvirtual

Invoked just before control is returned to the user.

Parameters
timeoutThe maximum amount of time to wait
Returns
True if the wait succeeded, false if a timeout occurred

This virtual method provides implementors with a way to add further constraints to the wait operation beyond the condition variable held internally by this CoreRunnable.

This method must return true if the timeout is indefinite.

Reimplemented from CoreRunnable.

virtual void BasicThread::DoRun ( std::shared_ptr< CoreObject > &&  refTracker)
protectedvirtual

Routine that sets up the necessary extranea before a call to Run

Clients who wish to trigger teardown may release the reference to the passed refTracker instance. If this thread is the last thread holding a reference to this context, then after the point where the reference is released, [this] will be deleted. Clients should be careful to hold their own references to refTracker before calling DoRun if they intend to reference member data on function return. This method will always release the shared pointer passed to it, typically as a last step before return, potentially triggering the case described above.

virtual void BasicThread::DoRunLoopCleanup ( std::shared_ptr< CoreContext > &&  ctxt,
std::shared_ptr< CoreObject > &&  refTracker 
)
protectedvirtual

Performs all cleanup operations that must take place after DoRun()

Parameters
ctxtThe last reference to the enclosing context held by this thread
refTrackerA reference tracker held for as long as the cleanup operation is incomplete

Reimplemented in CoreThread.

static void BasicThread::ForceCoreThreadReidentify ( void  )
static

Forces all Autowiring threads to reidentify themselves.

Calls SetThreadName() for each thread.

std::chrono::steady_clock::time_point BasicThread::GetCreationTime ( void  )

The thread creation time.

Returns
Returns the time when this thread was created.

If the thread has not yet run, this routine returns std::steady_clock::time_point::min

std::mutex& BasicThread::GetLock ( void  ) const
protected

Recovers a general lock used to synchronize entities in this thread internally.

std::shared_ptr<void> BasicThread::GetThread ( void  ) const
Returns
A void pointer to the underlying std::thread
ThreadPriority BasicThread::GetThreadPriority ( void  ) const
inline
Returns
The current thread priority
void BasicThread::GetThreadTimes ( std::chrono::milliseconds &  kernelTime,
std::chrono::milliseconds &  userTime 
)

Reports kernel and user mode running times for this thread.

This function is intended for debugging and performance reporting. It is used by the AutoNet server.

class PrimeGenerator : public BasicThread{
public:
void Run() override {
unsigned long int test = 2;
while (!ShouldStop())
{
for (unsigned long int i = test/2; i > 0 ; --i) {
if (i == 1) {
std::chrono::milliseconds kernelTime, userTime;
this->GetThreadTimes(kernelTime, userTime);
std::cout << "Calculated primes up to: " << test
<< " in " << (&kernelTime)->count() << " kernel ms "
<< "and " << (&userTime)->count() << " user ms."
<< std::endl;
}
if (test % i == 0) {break;}
}
test++;
}
}
};
CurrentContextPusher pusher(ctxt);
ctxt->Initiate();
ctxt->Wait(std::chrono::milliseconds(100));
ctxt->SignalShutdown(true);
bool BasicThread::IsCompleted ( void  ) const
Returns
True if this thread has transitioned to a completed state
static bool BasicThread::IsMainThread ( void  )
static
Returns
True if the calling thread is the main thread
bool BasicThread::OnStart ( )
overrideprotectedvirtual

Causes a new thread to be created in which the Run method will be invoked

Returns
True to indicate that the thread was started successfully, false if it was already started or cancelled

Note that this operation has an inherit race condition. Be careful to ensure that Start will not be called from more than one place on the same object. The thread will be invoked from the context which was active at the time the thread was created.

Reimplemented from CoreRunnable.

void BasicThread::OnStop ( bool  graceful)
overrideprotectedvirtual

Invoked by the base class Stop() method. Override this method to perform any needed cleanup.

Parameters
gracefulSpecifies whether the runnable should stop normally or whether it should exit as quickly as possible.

This method will be called at most once from a passive level.

Reimplemented from CoreRunnable.

Reimplemented in CoreThread.

virtual void BasicThread::OnStop ( void  )
inlinevirtual

Invoked by the base class Stop() method. Implement this method to perform any needed cleanup.

Do not perform any time-consuming operations in this callback; the method may be called from a time-sensitive context and unacceptable system performance could result if long-duration operations are undertaken here.

Override the OnStop(bool graceful) version of this function to handle immediate vs. graceful shutdown cleanup.

Reimplemented in CoreThread.

void BasicThread::PerformStatusUpdate ( const std::function< void()> &  fn) const
protected

Obtains a mutex, invokes the specified lambda function, and then updates the basic thread's state condition.

virtual void BasicThread::Run ( )
pure virtual

Begins thread execution.

Implement this function to perform the work to be done by this thread. Your Run() function implementation must exit when ShouldStop() becomes true.

BasicThreads can be stopped gracefully or immediately. Override OnStop(bool graceful) to implement different behavior for these two shutdown modes. For example, if the shutdown mode is immediate, you might abort any actions in progress, but if the mode is graceful, you might take time to save files, etc. This behavior is application defined. Autowiring does not impose its own requirements. You can also perform custom shutdown cleanup in an OnStop() implementation.

The default implementation of Run will simply call WaitForEvent in a loop until it's told to quit.

Implemented in CoreThread.

Examples:
ThreadExample.cpp.
void BasicThread::SetCurrentThreadName ( void  ) const
protected

Assigns a name to the thread, displayed in debuggers.

Some platforms allow the assignment of a thread name for identifying threads shown in a debugger window. This method provides a platform-independent way of doing setting this name for the current thread.

void BasicThread::SetThreadPriority ( ThreadPriority  threadPriority)
protected

Sets the thread priority of this thread

This method may be called while the thread is running, or before it starts to run. If it is invoked before the thread starts to run, the thread will take on the specified priority when it is started.

void BasicThread::WaitForStateUpdate ( const std::function< bool()> &  fn) const
protected

Waits until the specified lambda function returns true or the thread shuts down.

The lambda function is called repeatedly until it evaluates to true.


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