Ocean
Ocean::Thread Class Referenceabstract

This class implements a thread. More...

Inheritance diagram for Ocean::Thread:

Data Structures

class  ThreadId
 This class implements a platform independent wrapper for thread ids. More...
 

Public Types

enum  ThreadPriority {
  PRIORITY_IDLE , PRIORTY_BELOW_NORMAL , PRIORTY_NORMAL , PRIORTY_ABOVE_NORMAL ,
  PRIORTY_HIGH , PRIORTY_REALTIME
}
 Definition of different thread priority values. More...
 

Public Member Functions

 Thread (const std::string &name=std::string())
 Creates a new thread object. More...
 
 Thread (const unsigned int randomNumberSeedValue, const std::string &name=std::string())
 Creates a new thread object. More...
 
virtual ~Thread ()
 Destructs a thread object. More...
 
bool startThread ()
 Starts the thread. More...
 
void stopThread ()
 Informs the thread to stop. More...
 
bool terminateThread ()
 Terminates the thread. More...
 
bool joinThread (const unsigned int timeout=(unsigned int)(-1))
 Waits until this thread has been stopped. More...
 
bool shouldThreadStop () const
 Returns whether this thread should stop. More...
 
bool isThreadInvokedToStart () const
 Returns whether this thread has been invoked to start immediately. More...
 
bool isThreadActive () const
 Returns whether this thread is active. More...
 

Static Public Member Functions

static void sleep (unsigned int ms)
 Sleeps the calling thread for a given time. More...
 
static void giveUp ()
 Gives up the remaining thread time. More...
 
static ThreadId currentThreadId ()
 Returns the thread id of the current (calling) thread. More...
 
static ThreadPriority threadPriority ()
 Returns the priority of the current thread. More...
 
static bool setThreadPriority (const ThreadPriority priority)
 Sets the priority of the current thread. More...
 
template<typename TObject , typename TExpectedValue >
static bool waitForValue (TObject &object, const TExpectedValue &expectedValue, const double timeout=-1.0)
 Waits until an object/variable has an expected value. More...
 
template<typename TObject , typename TExpectedValue >
static bool waitForValue (TObject &object, const TExpectedValue &expectedValue, TemporaryScopedLock &temporaryScopedLock, const double timeout=-1.0)
 Waits until an object/variable has an expected value. More...
 
static int pthread_timedjoin_np (pthread_t thread, void **retval, const struct timespec *abstime)
 Implements a thread join function with timeout value. More...
 

Protected Types

typedef std::pair< pthread_t, bool > TimedJoinPair
 Definition of a pair holding a thread id and a boolean state. More...
 

Protected Member Functions

 Thread (const Thread &thread)=delete
 Disabled copy constructor. More...
 
void createThread ()
 Creates the thread itself. More...
 
void destroyThread ()
 Destroys the thread itself. More...
 
void stopThreadExplicitly (const unsigned int timeout=5000u)
 Tries to stop the thread gracefully. More...
 
virtual void threadRun ()=0
 This function has to be overloaded in derived class. More...
 
Threadoperator= (const Thread &thread)=delete
 The disabled assign operator. More...
 

Private Member Functions

void internalThreadRun ()
 Platform independent internal thread function calling the external thread function. More...
 

Static Private Member Functions

static void * pthread_timedjoin_np_helper (void *threadData)
 The helper function for the pthread_timedjoin_np() implementation. More...
 
static DWORD __stdcall staticThreadRun (void *data)
 Internal thread function calling the external thread function. More...
 
static void * staticThreadRun (void *data)
 Internal thread function calling the external thread function. More...
 

Private Attributes

HANDLE threadHandle_ = nullptr
 Internal windows thread handle. More...
 
pthread_t threadObject_ = 0
 Internal pthread object. More...
 
std::atomic< bool > threadShouldStop_ {false}
 Determines whether this thread should stop. More...
 
bool threadIsActive_ = false
 Determines whether this thread is actually running. More...
 
bool threadIsInvokedToStart_ = false
 Determines whether this thread has been invoked to start immediately. More...
 
std::string threadName_
 Name of the thread. More...
 
unsigned int threadRandomNumberSeedValue_ = 0u
 The seed value for random number generators. More...
 

Detailed Description

This class implements a thread.

The implementation can be used in two ways:
First: Derive an own class from this thread class and overwrite the internal Thread::threadRun() function.
This function will then be called once the thread has been started. If this run function returns the thread will be closed.
Second: Set the run callback function which will be called instead of the normal internal run function.
Similar to the first solution the thread will be closed after the callback function returns.
However, if the normal internal run function is overloaded by a derived call a possible defined callback function has no effect.

Each thread can be started using the Thread::startThread() function,
and stopped using the Thread::stopThread() function.
However, the stop function will not explicit terminate the thread, it sets the thread's should-stop-state only.
Therefore, an implementation using this thread class must check the thread's should-stop-state recurrently.
Use Thread::shouldThreadStop() to determine whether your implementation should stop the thread execution.

If the thread execution does not return after a Thread::stopThread() the thread can be kill in an explicit manner.
Beware: Such kind of rough termination should be avoided and in most cases evidences a dirty usage of the internal run function.

See this tutorial:

// Any class using the thread class as base class.
class Timer : protected Thread
{
public:
// Creates a new timer object.
Timer();
// Stars the timer.
void start();
// Stops the timer.
void stop()
private:
// Internal thread run function which overloaded the function from the thread class.
void threadRun() override;
};
Timer::Timer() :
Thread("Optional thread name")
{
// nothing to do here
// optional the thread could be started here,
// however we use the start function for this explicitly
}
void Timer::start()
{
}
void Timer::stop()
{
}
void Timer::threadRun()
{
// check whether this thread should stop execution
while (shouldThreadStop() == false)
{
// do anything a timer can do
// to avoid a very high CPU load it can be suitable to sleep this thread for a small time
sleep(1);
}
// now the run function will return and the thread will be closed
}
// Usage of the timer in any environment, here it is used in a main function
void main()
{
Timer timer;
timer.start();
// do anything in a e.g. message loop
timer.stop();
}
bool startThread()
Starts the thread.
void stopThread()
Informs the thread to stop.
static void sleep(unsigned int ms)
Sleeps the calling thread for a given time.
Thread(const std::string &name=std::string())
Creates a new thread object.
virtual void threadRun()=0
This function has to be overloaded in derived class.
bool shouldThreadStop() const
Returns whether this thread should stop.
See also
ThreadPool, Scheduler, Worker.

Member Typedef Documentation

◆ TimedJoinPair

typedef std::pair<pthread_t, bool> Ocean::Thread::TimedJoinPair
protected

Definition of a pair holding a thread id and a boolean state.

Member Enumeration Documentation

◆ ThreadPriority

Definition of different thread priority values.

Enumerator
PRIORITY_IDLE 

The thread runs if the system is idle.

PRIORTY_BELOW_NORMAL 

The thread has a priority below normal.

PRIORTY_NORMAL 

The thread has a normal priority.

PRIORTY_ABOVE_NORMAL 

The thread has a priority above normal.

PRIORTY_HIGH 

The thread has a high priority.

PRIORTY_REALTIME 

The thread has a real time priority.

Constructor & Destructor Documentation

◆ Thread() [1/3]

Ocean::Thread::Thread ( const std::string &  name = std::string())
explicit

Creates a new thread object.

The thread will be initialized with a seed value automatically generated by using RandomI::random32().

Parameters
nameOptional thread name which can be helpful for debugging tasks

◆ Thread() [2/3]

Ocean::Thread::Thread ( const unsigned int  randomNumberSeedValue,
const std::string &  name = std::string() 
)
explicit

Creates a new thread object.

Parameters
randomNumberSeedValueAn explicit seed value for the random number initialization, with range [0, infinity)
nameOptional thread name which can be helpful for debugging tasks

◆ ~Thread()

virtual Ocean::Thread::~Thread ( )
virtual

Destructs a thread object.

◆ Thread() [3/3]

Ocean::Thread::Thread ( const Thread thread)
protecteddelete

Disabled copy constructor.

Parameters
threadThe object that would be copied

Member Function Documentation

◆ createThread()

void Ocean::Thread::createThread ( )
protected

Creates the thread itself.

◆ currentThreadId()

static ThreadId Ocean::Thread::currentThreadId ( )
static

Returns the thread id of the current (calling) thread.

Returns
The thread id of the current thread

◆ destroyThread()

void Ocean::Thread::destroyThread ( )
protected

Destroys the thread itself.

However the thread must be terminated before!

◆ giveUp()

static void Ocean::Thread::giveUp ( )
static

Gives up the remaining thread time.

◆ internalThreadRun()

void Ocean::Thread::internalThreadRun ( )
private

Platform independent internal thread function calling the external thread function.

◆ isThreadActive()

bool Ocean::Thread::isThreadActive ( ) const

Returns whether this thread is active.

An active thread currently executes the internal thread function.

Returns
True, if so

◆ isThreadInvokedToStart()

bool Ocean::Thread::isThreadInvokedToStart ( ) const

Returns whether this thread has been invoked to start immediately.

Beware: No information is provided whether the thread is active already. However, to not start a thread invoked to start again, instead wait for the termination.

Returns
True, if so

◆ joinThread()

bool Ocean::Thread::joinThread ( const unsigned int  timeout = (unsigned int)(-1))

Waits until this thread has been stopped.

Parameters
timeoutThe number of milliseconds the caller thread will wait for this thread, -1 to wait infinite
Returns
True, if the thread has finished; False, if the timeout was exceeded

◆ operator=()

Thread& Ocean::Thread::operator= ( const Thread thread)
protecteddelete

The disabled assign operator.

Parameters
threadThe object that would be assigned

◆ pthread_timedjoin_np()

static int Ocean::Thread::pthread_timedjoin_np ( pthread_t  thread,
void **  retval,
const struct timespec *  abstime 
)
static

Implements a thread join function with timeout value.

Depending on the platform, this function may not exist in the default libraries (e.g., on Apple platforms).

Parameters
threadThe thread for which the ending function will wait
retvalThe optional return value of the thread
abstimeThe absolute timestamp after which the thread will have been ended
Returns
Zero (0), if succeeded

◆ pthread_timedjoin_np_helper()

static void* Ocean::Thread::pthread_timedjoin_np_helper ( void *  threadData)
staticprivate

The helper function for the pthread_timedjoin_np() implementation.

Parameters
threadDataThe thread's data
Returns
The return value of the thread

◆ setThreadPriority()

static bool Ocean::Thread::setThreadPriority ( const ThreadPriority  priority)
static

Sets the priority of the current thread.

Parameters
priorityThread priority to set
Returns
True, if succeeded

◆ shouldThreadStop()

bool Ocean::Thread::shouldThreadStop ( ) const

Returns whether this thread should stop.

Returns
True, if so
See also
stopThread().

◆ sleep()

static void Ocean::Thread::sleep ( unsigned int  ms)
static

Sleeps the calling thread for a given time.

Parameters
msSleeping time in ms

◆ startThread()

bool Ocean::Thread::startThread ( )

Starts the thread.

Returns
True, if the thread is not active

◆ staticThreadRun() [1/2]

static DWORD __stdcall Ocean::Thread::staticThreadRun ( void *  data)
staticprivate

Internal thread function calling the external thread function.

Parameters
dataThe data object which will contain the thread owner object
Returns
Thread return value

◆ staticThreadRun() [2/2]

static void* Ocean::Thread::staticThreadRun ( void *  data)
staticprivate

Internal thread function calling the external thread function.

Parameters
dataThe data object which will contain the thread owner object

◆ stopThread()

void Ocean::Thread::stopThread ( )

Informs the thread to stop.

see shouldThreadStop().

◆ stopThreadExplicitly()

void Ocean::Thread::stopThreadExplicitly ( const unsigned int  timeout = 5000u)
protected

Tries to stop the thread gracefully.

However, if the thread can not be stopped it is terminated in a rough manner.
Call this function in the destructor of a derived class.

Parameters
timeoutTime to wait for a graceful thread termination, in ms

◆ terminateThread()

bool Ocean::Thread::terminateThread ( )

Terminates the thread.

Beware: The thread will be terminated in a very rough way.

Returns
True, if the thread could be terminated

◆ threadPriority()

static ThreadPriority Ocean::Thread::threadPriority ( )
static

Returns the priority of the current thread.

Returns
Thread priority

◆ threadRun()

virtual void Ocean::Thread::threadRun ( )
protectedpure virtual

◆ waitForValue() [1/2]

template<typename TObject , typename TExpectedValue >
bool Ocean::Thread::waitForValue ( TObject &  object,
const TExpectedValue &  expectedValue,
const double  timeout = -1.0 
)
static

Waits until an object/variable has an expected value.

Parameters
objectReference to the object/variable whose value is to be checked
expectedValueThe value that the object/variable is expected to have
timeoutThe optional timeout of this function, in seconds, with range [0, infinity), -1 to wait forever
Returns
True, if the object/variable had the expected value when this function returned; False, if a timeout was defined and the timeout exceeded
Template Parameters
TObjectThe data type of the object/variable to check
TExpectedValueThe data type of the expected value

◆ waitForValue() [2/2]

template<typename TObject , typename TExpectedValue >
bool Ocean::Thread::waitForValue ( TObject &  object,
const TExpectedValue &  expectedValue,
TemporaryScopedLock temporaryScopedLock,
const double  timeout = -1.0 
)
static

Waits until an object/variable has an expected value.

The provided temporary scoped lock will be repeatingly locked and released while the function is waiting and while accessing the object/variable.
The temporary scoped lock needs to be locked before calling this function, and it will also be locked when the function returns.

Parameters
objectReference to the object/variable whose value is to be checked
expectedValueThe value that the object/variable is expected to have
temporaryScopedLockThe temporary scoped lock which needs to be locked when calling the function; will be locked when the function returns
timeoutThe optional timeout of this function, in seconds, with range [0, infinity), -1 to wait forever
Returns
True, if the object/variable had the expected value when this function returned; False, if a timeout was defined and the timeout exceeded
Template Parameters
TObjectThe data type of the object/variable to check
TExpectedValueThe data type of the expected value

Field Documentation

◆ threadHandle_

HANDLE Ocean::Thread::threadHandle_ = nullptr
private

Internal windows thread handle.

◆ threadIsActive_

bool Ocean::Thread::threadIsActive_ = false
private

Determines whether this thread is actually running.

◆ threadIsInvokedToStart_

bool Ocean::Thread::threadIsInvokedToStart_ = false
private

Determines whether this thread has been invoked to start immediately.

◆ threadName_

std::string Ocean::Thread::threadName_
private

Name of the thread.

◆ threadObject_

pthread_t Ocean::Thread::threadObject_ = 0
private

Internal pthread object.

◆ threadRandomNumberSeedValue_

unsigned int Ocean::Thread::threadRandomNumberSeedValue_ = 0u
private

The seed value for random number generators.

◆ threadShouldStop_

std::atomic<bool> Ocean::Thread::threadShouldStop_ {false}
private

Determines whether this thread should stop.


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