EtcPal  HEAD (unstable)
ETC Platform Abstraction Layer (EtcPal)
View other versions:
Thread Class Reference

Overview

A thread class, modeled after std::thread.

This class is similar to std::thread, with the key advantage that it will work on any threaded platform that EtcPal is ported for, including the embedded RTOS platforms. If your application or library does not need to run on these platforms, consider using std::thread instead.

There are a few differences from std::thread:

  • The thread is automatically joined on destruction (this matches the behavior of C++20's std::jthread)
  • The thread is not detachable; that is, once created, it must be joined before it is destroyed in all cases.
  • The thread has a Start() function - a previously default-constructed thread can be assigned some operation parameters, then started, without being reassigned to another instance.

This is one of the few EtcPal wrappers that does heap allocation, as the thread function and arguments need to be stored.

Public Member Functions

 Thread ()=default
 Create a new thread object which does not yet represent a thread.
 
template<class Function , class... Args, typename std::enable_if<!std::is_arithmetic< Function >::value, bool >::type = true>
 Thread (Function &&func, Args &&... args)
 Create a new thread object and associate it with a new thread of execution. More...
 
 Thread (unsigned int priority, unsigned int stack_size, const char *name, void *platform_data=nullptr)
 Create a new thread object which does not yet represent a thread, passing explicit parameters. More...
 
virtual ~Thread ()
 Destroy the thread object. More...
 
 Thread (Thread &&other) noexcept
 Move another thread into this thread. More...
 
Threadoperator= (Thread &&other) noexcept
 Move another thread into this thread. More...
 
 Thread (const Thread &other)=delete
 Deleted copy constructor - threads are not copyable.
 
Threadoperator= (const Thread &other)=delete
 Deleted copy assignment operator - threads are not copyable.
 
bool joinable () const noexcept
 Whether the thread object identifies an active thread of execution.
 
template<class Function , class... Args>
Error Start (Function &&func, Args &&... args)
 Associate this thread object with a new thread of execution. More...
 
Error Join (int timeout_ms=ETCPAL_WAIT_FOREVER) noexcept
 Wait for the thread to finish execution. More...
 
Error Terminate () noexcept
 Forcefully kill the thread. More...
 
Getters
unsigned int priority () const noexcept
 Get the priority of this thread (not valid on all platforms).
 
unsigned int stack_size () const noexcept
 Get the stack size of this thread in bytes (not valid on all platforms).
 
const char * name () const noexcept
 Get the name of this thread.
 
void * platform_data () const noexcept
 Get the platform-specific data of this thread.
 
const EtcPalThreadParamsparams () const noexcept
 Get a reference the parameters of this thread.
 
etcpal_thread_os_handle_t os_handle () const noexcept
 Get the native OS handle of this thread. More...
 
Setters
ThreadSetPriority (unsigned int priority) noexcept
 Set the priority of this thread. More...
 
ThreadSetStackSize (unsigned int stack_size) noexcept
 Set the stack size of this thread in bytes. More...
 
ThreadSetName (const char *name) noexcept
 Set the name of this thread. More...
 
ThreadSetName (const std::string &name) noexcept
 Set the name of this thread. More...
 
ThreadSetPlatformData (void *platform_data) noexcept
 Set the platform-specific parameter data. More...
 
ThreadSetParams (const EtcPalThreadParams &params) noexcept
 Set this thread's parameters from an existing EtcPalThreadParams struct. More...
 

Static Public Member Functions

static Error Sleep (unsigned int ms) noexcept
 Blocks the current thread for the specified number of milliseconds. More...
 
template<typename Rep , typename Period >
static Error Sleep (const std::chrono::duration< Rep, Period > &sleep_duration) noexcept
 Blocks the current thread for the specified duration. More...
 

Constructor & Destructor Documentation

◆ Thread() [1/3]

Thread ( Function &&  func,
Args &&...  args 
)

Create a new thread object and associate it with a new thread of execution.

Default thread parameters will be used. See the Start() function for more information.

Parameters
funcCallable object to execute in the new thread.
argsArguments to pass to func.
Exceptions
std::runtime_errorif Start() returns an error code.
Postcondition
joinable() == true

◆ Thread() [2/3]

Thread ( unsigned int  priority,
unsigned int  stack_size,
const char *  name,
void *  platform_data = nullptr 
)
inline

Create a new thread object which does not yet represent a thread, passing explicit parameters.

The thread is not running until Start() is called.

Parameters
priorityPriority of the thread.
stack_sizeStack size of the thread in bytes.
nameA name for the thread, maximum length ETCPAL_THREAD_NAME_MAX_LENGTH.
platform_dataPointer to a platform-specific parameter structure. See EtcPalThreadParams for more information.

◆ ~Thread()

~Thread ( )
inlinevirtual

Destroy the thread object.

If *this has a valid associated thread (joinable() == true), the thread is joined before the destructor finishes.

◆ Thread() [3/3]

Thread ( Thread &&  other)
inlinenoexcept

Move another thread into this thread.

If *this has a valid associated thread (joinable() == true), the behavior is undefined. After this call, *this has the parameters of other, and other is set to a default-constructed state.

Member Function Documentation

◆ Join()

Error Join ( int  timeout_ms = ETCPAL_WAIT_FOREVER)
inlinenoexcept

Wait for the thread to finish execution.

If timeout_ms is not given, or if ETCPAL_THREAD_HAS_TIMED_JOIN is false on this platform, blocks until the thread has exited. Otherwise, blocks up to timeout_ms waiting for the thread to exit.

Parameters
timeout_msHow long to wait for the thread to exit (default forever).
Returns
kEtcPalErrOk: The thread was stopped; joinable() is now false.
kEtcPalErrTimedOut: The thread did not join within the specified timeout.
kEtcPalErrInvalid: The thread was not running (joinable() == false).
Other codes translated from system error codes are possible.

◆ operator=()

Thread & operator= ( Thread &&  other)
inlinenoexcept

Move another thread into this thread.

If *this has a valid associated thread (joinable() == true), the behavior is undefined. After this call, *this has the parameters of other, and other is set to a default-constructed state.

◆ os_handle()

etcpal_thread_os_handle_t os_handle ( ) const
inlinenoexcept

Get the native OS handle of this thread.

Returns
The thread's OS handle, or ETCPAL_THREAD_OS_HANDLE_INVALID if the thread is not running (joinable() == false).

◆ SetName() [1/2]

Thread & SetName ( const char *  name)
inlinenoexcept

Set the name of this thread.

This function does not have any effect on the associated thread unless it is called on a default-constructed thread before Start() is called. The pointer passed to this function must remain valid until after Start() is called.

Parameters
nameName to set.
Returns
A reference to this thread, for method chaining.

◆ SetName() [2/2]

Thread & SetName ( const std::string &  name)
inlinenoexcept

Set the name of this thread.

This function does not have any effect on the associated thread unless it is called on a default-constructed thread before Start() is called. The string reference passed to this function must remain valid until after Start() is called.

Parameters
nameName to set.
Returns
A reference to this thread, for method chaining.

◆ SetParams()

Thread & SetParams ( const EtcPalThreadParams params)
inlinenoexcept

Set this thread's parameters from an existing EtcPalThreadParams struct.

This function does not have any effect on the associated thread unless it is called on a default-constructed thread before Start() is called.

Parameters
paramsEtcPalThreadParams to use when starting the thread.
Returns
A reference to this thread, for method chaining.

◆ SetPlatformData()

Thread & SetPlatformData ( void *  platform_data)
inlinenoexcept

Set the platform-specific parameter data.

This function does not have any effect on the associated thread unless it is called on a default-constructed thread before Start() is called. The pointer passed to this function must remain valid until after Start() is called.

Parameters
platform_dataPointer to platform-specific data structure.
Returns
A reference to this thread, for method chaining.

◆ SetPriority()

Thread & SetPriority ( unsigned int  priority)
inlinenoexcept

Set the priority of this thread.

Priority is not valid on all platforms. This function does not have any effect on the associated thread unless it is called on a default-constructed thread before Start() is called.

Parameters
priorityPriority to set.
Returns
A reference to this thread, for method chaining.

◆ SetStackSize()

Thread & SetStackSize ( unsigned int  stack_size)
inlinenoexcept

Set the stack size of this thread in bytes.

Stack size is not valid on all platforms. This function does not have any effect on the associated thread unless it is called on a default-constructed thread before Start() is called.

Parameters
stack_sizeStack size to set.
Returns
A reference to this thread, for method chaining.

◆ Sleep() [1/2]

Error Sleep ( const std::chrono::duration< Rep, Period > &  sleep_duration)
staticnoexcept

Blocks the current thread for the specified duration.

Note: Duration will be clamped to [0, UINT_MAX] milliseconds.

◆ Sleep() [2/2]

Error Sleep ( unsigned int  ms)
inlinestaticnoexcept

Blocks the current thread for the specified number of milliseconds.

Returns
kEtcPalErrOk: The sleep completed.
kEtcPalErrSys: The system call may have been interrupted and awoke early.

◆ Start()

Error Start ( Function &&  func,
Args &&...  args 
)

Associate this thread object with a new thread of execution.

The new thread of execution starts executing

std::invoke(decay_copy(std::forward<Function>(f)),
decay_copy(std::forward<Args>(args))...);

where decay_copy is defined as

template <class T>
std::decay<T>::type decay_copy(T&& v) { return std::forward<T>(v); }

Except that the calls to decay_copy are evaluated in the context of the caller, so that any exceptions thrown during evaluation and copying/moving of the arguments are thrown in the current thread, without starting the new thread.

Parameters
funcCallable object to execute in the new thread.
argsArguments to pass to func.
Returns
kEtcPalErrOk: The thread started successfully, joinable() is now true.
kEtcPalErrNoMem: Allocation failed while starting thread.
kEtcPalErrInvalid: The thread was already running (joinable() == true).
Other codes translated from system error codes are possible.

◆ Terminate()

Error Terminate ( )
inlinenoexcept

Forcefully kill the thread.

Be careful when using this function. Depending on the state of a thread when it is terminated, shared resources or memory could not be freed, resulting in memory leaks or deadlocks.

Returns
kEtcPalErrOk: The thread was terminated; joinable() is now false.
kEtcPalErrInvalid: The thread was not running (joinable() == false).
Other codes translated from system error codes are possible.

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