SDL3pp
A slim C++ wrapper for SDL3
Loading...
Searching...
No Matches
Classes | Typedefs | Functions | Variables
Thread Management

SDL offers cross-platform thread management functions. More...

Collaboration diagram for Thread Management:

Classes

struct  SDL::ThreadParam
 Safely wrap Thread for non owning parameters. More...
 
class  SDL::Thread
 The SDL thread object. More...
 
struct  SDL::ThreadRef
 Semi-safe reference for Thread. More...
 

Typedefs

using SDL::ThreadRaw = SDL_Thread *
 Alias to raw representation for Thread.
 
using SDL::ThreadPriority = SDL_ThreadPriority
 The SDL thread priority. More...
 
using SDL::ThreadState = SDL_ThreadState
 The SDL thread state. More...
 
using SDL::ThreadID = SDL_ThreadID
 A unique numeric ID that identifies a thread. More...
 
using SDL::ThreadFunction = SDL_ThreadFunction
 The function passed to Thread.Thread() as the new thread's entry point. More...
 
using SDL::ThreadCB = std::function< int()>
 The function passed to Thread.Thread() as the new thread's entry point. More...
 
using SDL::TLSDestructorCallback = SDL_TLSDestructorCallback
 The callback used to cleanup data passed to SetTLS. More...
 
using SDL::TLSID = AtomicInt
 Thread local storage ID. More...
 

Functions

Thread SDL::CreateThread (ThreadFunction fn, StringParam name, void *data)
 Create a new thread with a default stack size. More...
 
Thread SDL::CreateThreadWithProperties (PropertiesParam props)
 Create a new thread with with the specified properties. More...
 
const char * SDL::GetThreadName (ThreadParam thread)
 Get the thread name as it was specified in Thread.Thread(). More...
 
ThreadID SDL::GetCurrentThreadID ()
 Get the thread identifier for the current thread. More...
 
ThreadID SDL::GetThreadID (ThreadParam thread)
 Get the thread identifier for the specified thread. More...
 
void SDL::SetCurrentThreadPriority (ThreadPriority priority)
 Set the priority for the current thread. More...
 
void SDL::WaitThread (ThreadParam thread, int *status)
 Wait for a thread to finish. More...
 
ThreadState SDL::GetThreadState (ThreadParam thread)
 Get the current state of a thread. More...
 
void SDL::DetachThread (ThreadRaw thread)
 Let a thread clean up on exit without intervention. More...
 
void * SDL::GetTLS (TLSID *id)
 Get the current thread's value associated with a thread local storage ID. More...
 
void SDL::SetTLS (TLSID *id, const void *value, TLSDestructorCallback destructor)
 Set the current thread's value associated with a thread local storage ID. More...
 
void SDL::CleanupTLS ()
 Cleanup all TLS data for this thread. More...
 
const char * SDL::Thread::GetName () const
 Get the thread name as it was specified in Thread.Thread(). More...
 
ThreadID SDL::Thread::GetID () const
 Get the thread identifier for the specified thread. More...
 
static void SDL::Thread::SetCurrentPriority (ThreadPriority priority)
 Set the priority for the current thread. More...
 
void SDL::Thread::Wait (int *status)
 Wait for a thread to finish. More...
 
ThreadState SDL::Thread::GetState () const
 Get the current state of a thread. More...
 
void SDL::Thread::Detach ()
 Let a thread clean up on exit without intervention. More...
 

Variables

constexpr ThreadPriority SDL::THREAD_PRIORITY_LOW = SDL_THREAD_PRIORITY_LOW
 LOW.
 
constexpr ThreadPriority SDL::THREAD_PRIORITY_NORMAL
 NORMAL. More...
 
constexpr ThreadPriority SDL::THREAD_PRIORITY_HIGH
 HIGH. More...
 
constexpr ThreadPriority SDL::THREAD_PRIORITY_TIME_CRITICAL
 TIME_CRITICAL. More...
 
constexpr ThreadState SDL::THREAD_UNKNOWN
 The thread is not valid. More...
 
constexpr ThreadState SDL::THREAD_ALIVE
 The thread is currently running. More...
 
constexpr ThreadState SDL::THREAD_DETACHED
 The thread is detached and can't be waited on. More...
 
constexpr ThreadState SDL::THREAD_COMPLETE = SDL_THREAD_COMPLETE
 The thread has finished and should be cleaned up with Thread.Wait()
 

Detailed Description

These are mostly concerned with starting threads, setting their priority, and dealing with their termination.

In addition, there is support for Thread Local Storage (data that is unique to each thread, but accessed from a single key).

On platforms without thread support (such as Emscripten when built without pthreads), these functions still exist, but things like Thread.Thread() will report failure without doing anything.

If you're going to work with threads, you almost certainly need to have a good understanding of [CategoryMutex](CategoryMutex) as well.

Typedef Documentation

◆ ThreadCB

using SDL::ThreadCB = typedef std::function<int()>
Returns
a value that can be reported through Thread.Wait().
Since
This datatype is available since SDL 3.2.0.

◆ ThreadFunction

using SDL::ThreadFunction = typedef SDL_ThreadFunction
Parameters
datawhat was passed as data to Thread.Thread().
Returns
a value that can be reported through Thread.Wait().
Since
This datatype is available since SDL 3.2.0.

◆ ThreadID

using SDL::ThreadID = typedef SDL_ThreadID

These are different from Thread objects, which are generally what an application will operate on, but having a way to uniquely identify a thread can be useful at times.

Since
This datatype is available since SDL 3.2.0.
See also
Thread.GetID
GetCurrentThreadID

◆ ThreadPriority

using SDL::ThreadPriority = typedef SDL_ThreadPriority

SDL will make system changes as necessary in order to apply the thread priority. Code which attempts to control thread state related to priority should be aware that calling Thread.SetCurrentPriority may alter such state. SDL_HINT_THREAD_PRIORITY_POLICY can be used to control aspects of this behavior.

Since
This enum is available since SDL 3.2.0.

◆ ThreadState

using SDL::ThreadState = typedef SDL_ThreadState

The current state of a thread can be checked by calling Thread.GetState.

Since
This enum is available since SDL 3.2.0.
See also
Thread.GetState

◆ TLSDestructorCallback

using SDL::TLSDestructorCallback = typedef SDL_TLSDestructorCallback

This is called when a thread exits, to allow an app to free any resources.

Parameters
valuea pointer previously handed to SetTLS.
Since
This datatype is available since SDL 3.2.0.
See also
SetTLS

◆ TLSID

using SDL::TLSID = typedef AtomicInt

0 is the invalid ID. An app can create these and then set data for these IDs that is unique to each thread.

Since
This datatype is available since SDL 3.2.0.
See also
GetTLS
SetTLS

Function Documentation

◆ CleanupTLS()

void SDL::CleanupTLS ( )
inline

If you are creating your threads outside of SDL and then calling SDL functions, you should call this function before your thread exits, to properly clean up SDL memory.

Thread safety:
It is safe to call this function from any thread.
Since
This function is available since SDL 3.2.0.

◆ CreateThread()

Thread SDL::CreateThread ( ThreadFunction  fn,
StringParam  name,
void *  data 
)
inline

This is a convenience function, equivalent to calling Thread.Thread with the following properties set:

  • prop::thread.CREATE_ENTRY_FUNCTION_POINTER: fn
  • prop::thread.CREATE_NAME_STRING: name
  • prop::thread.CREATE_USERDATA_POINTER: data

Note that this "function" is actually a macro that calls an internal function with two extra parameters not listed here; they are hidden through preprocessor macros and are needed to support various C runtimes at the point of the function call. Language bindings that aren't using the C headers will need to deal with this.

Usually, apps should just call this function the same way on every platform and let the macros hide the details.

Parameters
fnthe ThreadFunction function to call in the new thread.
namethe name of the thread.
dataa pointer that is passed to fn.
Returns
an opaque pointer to the new thread object on success.
Exceptions
Erroron failure.
Since
This function is available since SDL 3.2.0.
See also
Thread.Thread
Thread.Wait

◆ CreateThreadWithProperties()

Thread SDL::CreateThreadWithProperties ( PropertiesParam  props)
inline

These are the supported properties:

  • prop::thread.CREATE_ENTRY_FUNCTION_POINTER: an ThreadFunction value that will be called at the start of the new thread's life. Required.
  • prop::thread.CREATE_NAME_STRING: the name of the new thread, which might be available to debuggers. Optional, defaults to nullptr.
  • prop::thread.CREATE_USERDATA_POINTER: an arbitrary app-defined pointer, which is passed to the entry function on the new thread, as its only parameter. Optional, defaults to nullptr.
  • prop::thread.CREATE_STACKSIZE_NUMBER: the size, in bytes, of the new thread's stack. Optional, defaults to 0 (system-defined default).

SDL makes an attempt to report prop::thread.CREATE_NAME_STRING to the system, so that debuggers can display it. Not all platforms support this.

Thread naming is a little complicated: Most systems have very small limits for the string length (Haiku has 32 bytes, Linux currently has 16, Visual C++ 6.0 has nine!), and possibly other arbitrary rules. You'll have to see what happens with your system's debugger. The name should be UTF-8 (but using the naming limits of C identifiers is a better bet). There are no requirements for thread naming conventions, so long as the string is null-terminated UTF-8, but these guidelines are helpful in choosing a name:

https://stackoverflow.com/questions/149932/naming-conventions-for-threads

If a system imposes requirements, SDL will try to munge the string for it (truncate, etc), but the original string contents will be available from Thread.GetName().

The size (in bytes) of the new stack can be specified with prop::thread.CREATE_STACKSIZE_NUMBER. Zero means "use the system default" which might be wildly different between platforms. x86 Linux generally defaults to eight megabytes, an embedded device might be a few kilobytes instead. You generally need to specify a stack that is a multiple of the system's page size (in many cases, this is 4 kilobytes, but check your system documentation).

Note that this "function" is actually a macro that calls an internal function with two extra parameters not listed here; they are hidden through preprocessor macros and are needed to support various C runtimes at the point of the function call. Language bindings that aren't using the C headers will need to deal with this.

The actual symbol in SDL is SDL_CreateThreadWithPropertiesRuntime, so there is no symbol clash, but trying to load an SDL shared library and look for "Thread.Thread" will fail.

Usually, apps should just call this function the same way on every platform and let the macros hide the details.

Parameters
propsthe properties to use.
Returns
an opaque pointer to the new thread object on success.
Exceptions
Erroron failure.
Since
This function is available since SDL 3.2.0.
See also
Thread.Thread
Thread.Wait

◆ Detach()

void SDL::Thread::Detach ( )
inline

A thread may be "detached" to signify that it should not remain until another thread has called Thread.Wait() on it. Detaching a thread is useful for long-running threads that nothing needs to synchronize with or further manage. When a detached thread is done, it simply goes away.

There is no way to recover the return code of a detached thread. If you need this, don't detach the thread and instead use Thread.Wait().

Once a thread is detached, you should usually assume the Thread isn't safe to reference again, as it will become invalid immediately upon the detached thread's exit, instead of remaining until someone has called Thread.Wait() to finally clean it up. As such, don't detach the same thread more than once.

If a thread has already exited when passed to Thread.Detach(), it will stop waiting for a call to Thread.Wait() and clean up immediately. It is not safe to detach a thread that might be used with Thread.Wait().

You may not call Thread.Wait() on a thread that has been detached. Use either that function or this one, but not both, or behavior is undefined.

It is safe to pass nullptr to this function; it is a no-op.

          Thread.Thread() call that started this thread.
Since
This function is available since SDL 3.2.0.
See also
Thread.Thread
Thread.Wait

◆ DetachThread()

void SDL::DetachThread ( ThreadRaw  thread)
inline

A thread may be "detached" to signify that it should not remain until another thread has called Thread.Wait() on it. Detaching a thread is useful for long-running threads that nothing needs to synchronize with or further manage. When a detached thread is done, it simply goes away.

There is no way to recover the return code of a detached thread. If you need this, don't detach the thread and instead use Thread.Wait().

Once a thread is detached, you should usually assume the Thread isn't safe to reference again, as it will become invalid immediately upon the detached thread's exit, instead of remaining until someone has called Thread.Wait() to finally clean it up. As such, don't detach the same thread more than once.

If a thread has already exited when passed to Thread.Detach(), it will stop waiting for a call to Thread.Wait() and clean up immediately. It is not safe to detach a thread that might be used with Thread.Wait().

You may not call Thread.Wait() on a thread that has been detached. Use either that function or this one, but not both, or behavior is undefined.

It is safe to pass nullptr to this function; it is a no-op.

Parameters
threadthe Thread pointer that was returned from the Thread.Thread() call that started this thread.
Since
This function is available since SDL 3.2.0.
See also
Thread.Thread
Thread.Wait

◆ GetCurrentThreadID()

ThreadID SDL::GetCurrentThreadID ( )
inline

This thread identifier is as reported by the underlying operating system. If SDL is running on a platform that does not support threads the return value will always be zero.

This function also returns a valid thread ID when called from the main thread.

Returns
the ID of the current thread.
Since
This function is available since SDL 3.2.0.
See also
Thread.GetID

◆ GetID()

ThreadID SDL::Thread::GetID ( ) const
inline

This thread identifier is as reported by the underlying operating system. If SDL is running on a platform that does not support threads the return value will always be zero.

Returns
the ID of the specified thread, or the ID of the current thread if thread is nullptr.
Since
This function is available since SDL 3.2.0.
See also
GetCurrentThreadID

◆ GetName()

const char * SDL::Thread::GetName ( ) const
inline
Returns
a pointer to a UTF-8 string that names the specified thread, or nullptr if it doesn't have a name.
Since
This function is available since SDL 3.2.0.

◆ GetState()

ThreadState SDL::Thread::GetState ( ) const
inline
Returns
the current state of a thread, or THREAD_UNKNOWN if the thread isn't valid.
Since
This function is available since SDL 3.2.0.
See also
ThreadState

◆ GetThreadID()

ThreadID SDL::GetThreadID ( ThreadParam  thread)
inline

This thread identifier is as reported by the underlying operating system. If SDL is running on a platform that does not support threads the return value will always be zero.

Parameters
threadthe thread to query.
Returns
the ID of the specified thread, or the ID of the current thread if thread is nullptr.
Since
This function is available since SDL 3.2.0.
See also
GetCurrentThreadID

◆ GetThreadName()

const char * SDL::GetThreadName ( ThreadParam  thread)
inline
Parameters
threadthe thread to query.
Returns
a pointer to a UTF-8 string that names the specified thread, or nullptr if it doesn't have a name.
Since
This function is available since SDL 3.2.0.

◆ GetThreadState()

ThreadState SDL::GetThreadState ( ThreadParam  thread)
inline
Parameters
threadthe thread to query.
Returns
the current state of a thread, or THREAD_UNKNOWN if the thread isn't valid.
Since
This function is available since SDL 3.2.0.
See also
ThreadState

◆ GetTLS()

void * SDL::GetTLS ( TLSID id)
inline
Parameters
ida pointer to the thread local storage ID, may not be nullptr.
Returns
the value associated with the ID for the current thread or nullptr if no value has been set; call GetError() for more information.
Thread safety:
It is safe to call this function from any thread.
Since
This function is available since SDL 3.2.0.
See also
SetTLS

◆ SetCurrentPriority()

void SDL::Thread::SetCurrentPriority ( ThreadPriority  priority)
inlinestatic

Note that some platforms will not let you alter the priority (or at least, promote the thread to a higher priority) at all, and some require you to be an administrator account. Be prepared for this to fail.

Parameters
prioritythe ThreadPriority to set.
Exceptions
Erroron failure.
Since
This function is available since SDL 3.2.0.

◆ SetCurrentThreadPriority()

void SDL::SetCurrentThreadPriority ( ThreadPriority  priority)
inline

Note that some platforms will not let you alter the priority (or at least, promote the thread to a higher priority) at all, and some require you to be an administrator account. Be prepared for this to fail.

Parameters
prioritythe ThreadPriority to set.
Exceptions
Erroron failure.
Since
This function is available since SDL 3.2.0.

◆ SetTLS()

void SDL::SetTLS ( TLSID id,
const void *  value,
TLSDestructorCallback  destructor 
)
inline

If the thread local storage ID is not initialized (the value is 0), a new ID will be created in a thread-safe way, so all calls using a pointer to the same ID will refer to the same local storage.

Note that replacing a value from a previous call to this function on the same thread does not call the previous value's destructor!

destructor can be nullptr; it is assumed that value does not need to be cleaned up if so.

Parameters
ida pointer to the thread local storage ID, may not be nullptr.
valuethe value to associate with the ID for the current thread.
destructora function called when the thread exits, to free the value, may be nullptr.
Exceptions
Erroron failure.
Thread safety:
It is safe to call this function from any thread.
Since
This function is available since SDL 3.2.0.
See also
GetTLS

◆ Wait()

void SDL::Thread::Wait ( int *  status)
inline

Threads that haven't been detached will remain until this function cleans them up. Not doing so is a resource leak.

Once a thread has been cleaned up through this function, the Thread that references it becomes invalid and should not be referenced again. As such, only one thread may call Thread.Wait() on another.

The return code from the thread function is placed in the area pointed to by status, if status is not nullptr.

You may not wait on a thread that has been used in a call to Thread.Detach(). Use either that function or this one, but not both, or behavior is undefined.

It is safe to pass a nullptr thread to this function; it is a no-op.

Note that the thread pointer is freed by this function and is not valid afterward.

          Thread.Thread() call that started this thread.
Parameters
statusa pointer filled in with the value returned from the thread function by its 'return', or -1 if the thread has been detached or isn't valid, may be nullptr.
Since
This function is available since SDL 3.2.0.
See also
Thread.Thread
Thread.Detach

◆ WaitThread()

void SDL::WaitThread ( ThreadParam  thread,
int *  status 
)
inline

Threads that haven't been detached will remain until this function cleans them up. Not doing so is a resource leak.

Once a thread has been cleaned up through this function, the Thread that references it becomes invalid and should not be referenced again. As such, only one thread may call Thread.Wait() on another.

The return code from the thread function is placed in the area pointed to by status, if status is not nullptr.

You may not wait on a thread that has been used in a call to Thread.Detach(). Use either that function or this one, but not both, or behavior is undefined.

It is safe to pass a nullptr thread to this function; it is a no-op.

Note that the thread pointer is freed by this function and is not valid afterward.

Parameters
threadthe Thread pointer that was returned from the Thread.Thread() call that started this thread.
statusa pointer filled in with the value returned from the thread function by its 'return', or -1 if the thread has been detached or isn't valid, may be nullptr.
Since
This function is available since SDL 3.2.0.
See also
Thread.Thread
Thread.Detach

Variable Documentation

◆ THREAD_ALIVE

constexpr ThreadState SDL::THREAD_ALIVE
constexpr
Initial value:
=
SDL_THREAD_ALIVE

◆ THREAD_DETACHED

constexpr ThreadState SDL::THREAD_DETACHED
constexpr
Initial value:
=
SDL_THREAD_DETACHED

◆ THREAD_PRIORITY_HIGH

constexpr ThreadPriority SDL::THREAD_PRIORITY_HIGH
constexpr
Initial value:
=
SDL_THREAD_PRIORITY_HIGH

◆ THREAD_PRIORITY_NORMAL

constexpr ThreadPriority SDL::THREAD_PRIORITY_NORMAL
constexpr
Initial value:
=
SDL_THREAD_PRIORITY_NORMAL

◆ THREAD_PRIORITY_TIME_CRITICAL

constexpr ThreadPriority SDL::THREAD_PRIORITY_TIME_CRITICAL
constexpr
Initial value:
=
SDL_THREAD_PRIORITY_TIME_CRITICAL

◆ THREAD_UNKNOWN

constexpr ThreadState SDL::THREAD_UNKNOWN
constexpr
Initial value:
=
SDL_THREAD_UNKNOWN