Autowiring  1.0.3
A C++ Inversion of Control Framework
CoreThread Class Reference

Provides a dispatch queue that creates a thread to run jobs (in the form of lambda functions) in the order added. More...

#include <CoreThread.h>

Inheritance diagram for CoreThread:
BasicThread DispatchQueue ContextMember CoreRunnable

Public Member Functions

 CoreThread (const char *pName=nullptr)
 
void OnStop (void) override
 Invoked when the thread should stop. Implement this method to perform any needed cleanup. More...
 
void OnStop (bool graceful) override final
 Invoked when the thread should stop. Override to perform custom handling when the thread is told to stop. More...
 
void Run (void) override
 Begins thread execution. More...
 
- Public Member Functions inherited from BasicThread
 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
 
- 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.
 
- Public Member Functions inherited from DispatchQueue
virtual ~DispatchQueue (void)
 Runs down the dispatch queue without calling anything More...
 
void Abort (void)
 Causes the current dispatch queue to be dumped if it's non-empty More...
 
void AddExisting (std::unique_ptr< autowiring::DispatchThunkBase > &&pBase)
 Explicit overload for already-constructed dispatch thunk types More...
 
bool AreAnyDispatchersReady (void) const
 
bool Barrier (std::chrono::nanoseconds timeout)
 Blocks until all dispatchers on the DispatchQueue at the time of the call have been dispatched More...
 
void Barrier (void)
 Identical to the timed version of Barrier, but does not time out More...
 
bool Cancel (void)
 Causes the very first lambda on the dispatch queue to be deleted without running it More...
 
int DispatchAllEvents (void)
 Similar to DispatchEvent, but will attempt to dispatch all events currently queued More...
 
bool DispatchEvent (void)
 Similar to WaitForEvent, but does not block More...
 
size_t GetDispatchQueueLength (void) const
 
void operator+= (DispatchQueue &&rhs)
 Extracts the contents of the dispatch queue on the right-hand side for handling by this queue More...
 
template<class Rep , class Period >
DispatchThunkDelayedExpressionRel operator+= (std::chrono::duration< Rep, Period > rhs)
 Overload for the introduction of a delayed dispatch thunk More...
 
DispatchThunkDelayedExpressionAbs operator+= (std::chrono::steady_clock::time_point rhs)
 Overload for absolute-time based delayed dispatch thunk More...
 
void operator+= (autowiring::DispatchThunkDelayed &&rhs)
 Directly pends a delayed dispatch thunk More...
 
template<class _Fx >
bool operator+= (_Fx &&fx)
 Generic overload which will pend an arbitrary dispatch type More...
 
void Rundown (void)
 Graceful version of Abort More...
 
std::chrono::steady_clock::time_point SuggestSoonestWakeupTimeUnsafe (std::chrono::steady_clock::time_point latestTime) const
 Recommends a point in time to wake up to check for events More...
 
bool TryDispatchEvent (void)
 Similar to WaitForEvent, but does not block More...
 
void WaitForEvent (void)
 Waits until a lambda function is ready to run in this thread's dispatch queue, dispatches the function, and then returns. More...
 
bool WaitForEvent (std::chrono::milliseconds milliseconds)
 Waits until a lambda function in the dispatch queue is ready to run or the specified time period elapses, whichever comes first. More...
 
bool WaitForEvent (std::chrono::steady_clock::time_point wakeTime)
 Waits until a lambda function in the dispatch queue is ready to run or the specified time is reached, whichever comes first. More...
 
void WakeAllWaitingThreads (void)
 Causes all calls to WaitForEvent to return control to their callers More...
 

Protected Member Functions

virtual void DoRunLoopCleanup (std::shared_ptr< CoreContext > &&ctxt, std::shared_ptr< CoreObject > &&refTracker) override
 Overridden here so we can rundown the dispatch queue More...
 
- Protected Member Functions inherited from BasicThread
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...
 
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 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
 
- Protected Member Functions inherited from DispatchQueue
void DispatchEventUnsafe (std::unique_lock< std::mutex > &lk)
 Similar to DispatchEvent, except assumes that the dispatch lock is currently held More...
 
virtual void OnPended (std::unique_lock< std::mutex > &&lk)
 Utility virtual, called whenever a new event is deferred More...
 
void PendExisting (std::unique_lock< std::mutex > &&lk, autowiring::DispatchThunkBase *thunk)
 Attaches an element to the end of the dispatch queue without any checks. More...
 
bool PromoteReadyDispatchersUnsafe (void)
 Moves all ready events from the delayed queue into the dispatch queue More...
 
void SetDispatcherCap (size_t dispatchCap)
 Updates the upper bound on the number of allowed pending dispatchers More...
 
void TryDispatchEventUnsafe (std::unique_lock< std::mutex > &lk)
 Similar to TryDispatchEvent, except assumes that the dispatch lock is currently held More...
 

Additional Inherited Members

- Static Public Member Functions inherited from BasicThread
static void ForceCoreThreadReidentify (void)
 Forces all Autowiring threads to reidentify themselves. More...
 
static bool IsMainThread (void)
 

Detailed Description

Provides a dispatch queue that creates a thread to run jobs (in the form of lambda functions) in the order added.

Create a CoreThread object by autowiring it to a context. You can then use the overloaded "+=" operator to add lambda functions to the dispatch queue. The core thread instance executes the functions in order.

CurrentContextPusher pusher(ctxt);
ctxt->Initiate();
*runner += []{
std::cout << "Job ran." << std::endl;
};
int x = 0;
auto func = [&x]{
std::cout << "Value of x: " << x << std::endl;
};
x = 4;
*runner += func;
ctxt->SignalShutdown(true);

When the CoreThread object receives the signal to shutdown, i.e from CoreContext::SignalShutdown(bool graceful), shutdown behavior depends on the graceful parameter. For graceful shutdown, the class completes the current job queue, but does not allow new jobs to be added to the queue. For immediate shutdown, the job queue is abandoned and the current job aborted.

Examples:
AutoNetExample.cpp, and ThreadExample.cpp.

Constructor & Destructor Documentation

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

Constructs a core thread object with an optional name.

The name assigned to a thread is visible in some debuggers.

Parameters
pNameAn optional name for this thread.

Member Function Documentation

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

Overridden here so we can rundown the dispatch queue

Reimplemented from BasicThread.

void CoreThread::OnStop ( void  )
inlineoverridevirtual

Invoked when the thread should stop. Implement this method to perform any needed cleanup.

This method is called before the dispatch queue is aborted or run down. Users wishing to perform operations gracefully during termination should pend these operations as lambdas to the thread's dispatch queue; these lambdas will be invoked if graceful termination is requested, and destroyed without invocation otherwise.

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.

The base implementation of this method is guaranteed to do nothing.

Reimplemented from BasicThread.

void CoreThread::OnStop ( bool  graceful)
finaloverridevirtual

Invoked when the thread should stop. Override to perform custom handling when the thread is told to stop.

Parameters
gracefulSet to true to rundown the dispatch queue before quitting.

This method is called when the thread should stop. When invoked, the value of CoreThread::ShouldStop is guaranteed to be true.

The default behavior is to terminate the job queue immediately if graceful is false. Otherwise, existing jobs in the queue are executed, but no new functions can be added to the dispatch queue.

Derived classes are not required to call CoreThread::OnStop.

Reimplemented from BasicThread.

void CoreThread::Run ( void  )
overridevirtual

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.

Implements BasicThread.


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