libpromeki main
PROfessional MEdia toolKIt
 
Loading...
Searching...
No Matches
Thread Class Reference

Wrapper around std::thread with a built-in EventLoop. More...

#include <thread.h>

Inheritance diagram for Thread:
Collaboration diagram for Thread:

Public Types

using NativeHandle = std::thread::native_handle_type
 Platform-specific native thread handle type.
 
- Public Types inherited from ObjectBase
using SlotVariantFunc = std::function< void(const VariantList &)>
 Function type for invoking a slot with a list of Variants.
 

Public Member Functions

 Thread (ObjectBase *parent=nullptr)
 Constructs a Thread (spawned mode).
 
virtual ~Thread ()
 Destructor. Waits for the thread if still running.
 
void start (size_t stackSize=0)
 Starts the thread.
 
Error wait (unsigned int timeoutMs=0)
 Waits for the thread to finish.
 
EventLoopthreadEventLoop () const
 Returns the EventLoop associated with this thread.
 
void quit (int returnCode=0)
 Requests the thread's event loop to quit.
 
int exitCode () const
 Returns the exit code from the thread's event loop.
 
bool isRunning () const
 Returns whether the thread is currently running.
 
bool isAdopted () const
 Returns whether this is an adopted thread.
 
bool isCurrentThread () const
 Returns whether the calling thread is this thread.
 
uint64_t nativeId () const
 Returns the OS-native thread ID.
 
SchedulePolicy schedulePolicy () const
 Returns the current scheduling policy of this thread.
 
int priority () const
 Returns the current priority of this thread.
 
Error setPriority (int priority, SchedulePolicy policy=SchedulePolicy::Default)
 Sets the scheduling policy and priority for this thread.
 
String name () const
 Returns the name of this thread.
 
void setName (const String &name)
 Sets the name of this thread.
 
Set< int > affinity () const
 Returns the set of CPU cores this thread is allowed to run on.
 
Error setAffinity (const Set< int > &cpus)
 Restricts this thread to run on the specified CPU cores.
 
 PROMEKI_SIGNAL (started)
 Emitted when the thread starts running.
 
 PROMEKI_SIGNAL (finished, int)
 Emitted when the thread finishes (carries the event loop exit code).
 
- Public Member Functions inherited from ObjectBase
 ObjectBase (ObjectBase *p=nullptr)
 Default ObjectBase constructor.
 
virtual ~ObjectBase ()
 Destructor. Emits aboutToDestroy, detaches from parent, and destroys children.
 
ObjectBaseparent () const
 Returns the parent object, if one. nullptr if none.
 
void setParent (ObjectBase *p)
 Sets the parent of this object. If the object already has a parent, it will be removed as a child from the old parent and added as a child to the new one.
 
const ObjectBaseListchildList () const
 Returns a list of children of this object.
 
template<typename... Args>
int registerSlot (Slot< Args... > *slot)
 Registers a slot with this object and assigns it an ID.
 
EventLoopeventLoop () const
 Returns the EventLoop this object is affiliated with.
 
void moveToThread (EventLoop *loop)
 Changes the EventLoop affinity of this object.
 
int startTimer (unsigned int intervalMs, bool singleShot=false)
 Starts a timer on this object's EventLoop.
 
void stopTimer (int timerId)
 Stops a timer previously started with startTimer().
 
template<typename... Args>
PROMEKI_NAMESPACE_BEGIN void connect (Signal< Args... > *signal, Slot< Args... > *slot)
 

Static Public Member Functions

static ThreadadoptCurrentThread ()
 Adopts the calling thread as a Thread object.
 
static ThreadcurrentThread ()
 Returns the Thread object for the calling thread.
 
static uint64_t currentNativeId ()
 Returns the OS-native thread ID of the calling thread.
 
static int priorityMin (SchedulePolicy policy=SchedulePolicy::Default)
 Returns the minimum priority for a scheduling policy.
 
static int priorityMax (SchedulePolicy policy=SchedulePolicy::Default)
 Returns the maximum priority for a scheduling policy.
 
static unsigned int idealThreadCount ()
 Returns the number of hardware threads available.
 
- Static Public Member Functions inherited from ObjectBase
static const MetaInfometaInfo ()
 Returns the MetaInfo for the ObjectBase class.
 
template<typename... Args>
static void connect (Signal< Args... > *signal, Slot< Args... > *slot)
 connects a signal and slot together. This function assumes both the signal and slot exist in a ObjectBase or derived object
 

Protected Member Functions

virtual void run ()
 Override for custom thread behavior.
 
- Protected Member Functions inherited from ObjectBase
ObjectBasesignalSender ()
 Returns the ObjectBase that emitted the signal currently being handled.
 
virtual void event (Event *e)
 Called by EventLoop to deliver events to this object.
 
virtual void timerEvent (TimerEvent *e)
 Called when a timer fires for this object.
 

Additional Inherited Members

- Public Attributes inherited from ObjectBase
Signal< ObjectBase * > aboutToDestroySignal = Signal< ObjectBase * >(this, aboutToDestroySignalName)
 
- Static Public Attributes inherited from ObjectBase
static constexpr const charaboutToDestroySignalName = PROMEKI_STRINGIFY( aboutToDestroy ) "(" PROMEKI_STRINGIFY_ARGS( ObjectBase * ) ")"
 
static SignalMeta aboutToDestroySignalMeta = SignalMeta(metaInfo(), aboutToDestroySignalName)
 

Detailed Description

Wrapper around std::thread with a built-in EventLoop.

Derives from ObjectBase so it participates in parent/child tree and signal/slot. Operates in two modes:

  1. Spawned threadstart() creates a std::thread, builds an EventLoop on it, and calls run(). The Thread object itself lives on the creating thread.
  2. Adopted thread — wraps an already-running thread (e.g. main). No std::thread is owned. start() is a no-op. Created by adoptCurrentThread().

Constructor & Destructor Documentation

◆ Thread()

Thread::Thread ( ObjectBase parent = nullptr)

Constructs a Thread (spawned mode).

Parameters
parentOptional parent ObjectBase.

Member Function Documentation

◆ adoptCurrentThread()

static Thread * Thread::adoptCurrentThread ( )
static

Adopts the calling thread as a Thread object.

Used by Application for the main thread. The returned Thread is not owned by anyone — the caller manages its lifetime.

Returns
A new Thread representing the current thread.

◆ affinity()

Set< int > Thread::affinity ( ) const

Returns the set of CPU cores this thread is allowed to run on.

The thread must be running. Returns an empty set if the thread is not running, on error, or if the platform does not support CPU affinity queries.

Returns
A set of zero-based CPU core indices.

◆ currentNativeId()

static uint64_t Thread::currentNativeId ( )
static

Returns the OS-native thread ID of the calling thread.

On Linux this is the kernel TID (gettid()), on macOS the pthread thread ID (pthread_threadid_np()), and on Windows the Win32 thread ID (GetCurrentThreadId()).

Returns
The native thread ID as a 64-bit unsigned integer.

◆ currentThread()

static Thread * Thread::currentThread ( )
static

Returns the Thread object for the calling thread.

Returns
The current thread's Thread, or nullptr if none.

◆ exitCode()

int Thread::exitCode ( ) const
inline

Returns the exit code from the thread's event loop.

Only meaningful after the thread has finished.

Returns
The exit code, or 0 if not yet available.

◆ idealThreadCount()

static unsigned int Thread::idealThreadCount ( )
static

Returns the number of hardware threads available.

Wraps std::thread::hardware_concurrency(). Returns 0 if the value cannot be determined.

Returns
The number of concurrent threads supported.

◆ isAdopted()

bool Thread::isAdopted ( ) const
inline

Returns whether this is an adopted thread.

Returns
true for adopted threads, false for spawned.

◆ isCurrentThread()

bool Thread::isCurrentThread ( ) const
inline

Returns whether the calling thread is this thread.

Returns
true if the caller is running on this thread.

◆ isRunning()

bool Thread::isRunning ( ) const
inline

Returns whether the thread is currently running.

Returns
true if the thread is running.

◆ name()

String Thread::name ( ) const

Returns the name of this thread.

Returns the name previously set by setName(), or an empty string if no name has been set.

Returns
The thread name.

◆ nativeId()

uint64_t Thread::nativeId ( ) const
inline

Returns the OS-native thread ID.

For spawned threads this is captured at thread start. For adopted threads it is captured at adoption time. Returns 0 if the thread has not yet started.

Returns
The native thread ID as a 64-bit unsigned integer.

◆ priority()

int Thread::priority ( ) const

Returns the current priority of this thread.

The thread must be running. Returns 0 if the thread is not running or on error.

Returns
The current priority value.

◆ priorityMax()

static int Thread::priorityMax ( SchedulePolicy  policy = SchedulePolicy::Default)
static

Returns the maximum priority for a scheduling policy.

Parameters
policyThe scheduling policy to query.
Returns
The maximum valid priority value.

◆ priorityMin()

static int Thread::priorityMin ( SchedulePolicy  policy = SchedulePolicy::Default)
static

Returns the minimum priority for a scheduling policy.

Parameters
policyThe scheduling policy to query.
Returns
The minimum valid priority value.

◆ PROMEKI_SIGNAL() [1/2]

Thread::PROMEKI_SIGNAL ( finished  ,
int   
)

Emitted when the thread finishes (carries the event loop exit code).

Signal:

◆ PROMEKI_SIGNAL() [2/2]

Thread::PROMEKI_SIGNAL ( started  )

Emitted when the thread starts running.

Signal:

◆ quit()

void Thread::quit ( int  returnCode = 0)

Requests the thread's event loop to quit.

Parameters
returnCodeThe exit code for the event loop.

◆ run()

virtual void Thread::run ( )
protectedvirtual

Override for custom thread behavior.

Default implementation runs the thread's EventLoop via exec().

◆ schedulePolicy()

SchedulePolicy Thread::schedulePolicy ( ) const

Returns the current scheduling policy of this thread.

The thread must be running. Returns SchedulePolicy::Default if the thread is not running or on error.

Returns
The current scheduling policy.

◆ setAffinity()

Error Thread::setAffinity ( const Set< int > &  cpus)

Restricts this thread to run on the specified CPU cores.

The thread must be running. An empty set clears any affinity restriction, allowing the thread to run on all available cores.

Parameters
cpusA set of zero-based CPU core indices.
Returns
Error::Ok on success, Error::Invalid if the thread is not running, Error::LibraryFailure on OS-level failure, Error::NotSupported on unsupported platforms.

◆ setName()

void Thread::setName ( const String name)

Sets the name of this thread.

The name is always stored locally. On supported platforms the OS-level thread name is also updated so that the name appears in debuggers and system tools (e.g. top -H, htop, ps -L).

If called before start(), the name is applied when the thread starts. The OS name is silently truncated to the platform limit (typically 15 characters on Linux/macOS).

On macOS the OS name can only be set from the thread itself, so cross-thread setName() updates the local name but not the OS name.

The logger's cached thread name is automatically updated when setName() is called from the thread itself.

Parameters
nameThe name to assign.

◆ setPriority()

Error Thread::setPriority ( int  priority,
SchedulePolicy  policy = SchedulePolicy::Default 
)

Sets the scheduling policy and priority for this thread.

The thread must be running. Real-time policies (Fifo, RoundRobin) typically require elevated privileges.

Parameters
priorityThe priority value. Use priorityMin() and priorityMax() to determine the valid range for the given policy.
policyThe scheduling policy to apply.
Returns
Error::Ok on success, Error::Invalid if the thread is not running, Error::LibraryFailure on OS-level failure.

◆ start()

void Thread::start ( size_t  stackSize = 0)

Starts the thread.

Creates an EventLoop on the new thread and calls run(). No-op for adopted threads or if already running.

Parameters
stackSizeThe stack size in bytes for the new thread. Zero (the default) uses the system default stack size. Ignored for adopted threads.

◆ threadEventLoop()

EventLoop * Thread::threadEventLoop ( ) const

Returns the EventLoop associated with this thread.

For spawned threads: valid after start(), before wait(). For adopted threads: returns the EventLoop currently active on that thread (looked up lazily, so it is valid as soon as an EventLoop is created on the adopted thread).

Returns
The thread's EventLoop, or nullptr.

◆ wait()

Error Thread::wait ( unsigned int  timeoutMs = 0)

Waits for the thread to finish.

For spawned threads, blocks until the thread exits or the timeout expires. If the timeout expires the thread is still running and the caller may retry or call quit() first.

Parameters
timeoutMsMaximum wait time in milliseconds. Zero (the default) waits indefinitely.
Returns
Error::Ok on success, Error::Invalid for adopted threads, Error::Timeout if the wait timed out.

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