1/*
2 Simple DirectMedia Layer
3 Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>
4
5 This software is provided 'as-is', without any express or implied
6 warranty. In no event will the authors be held liable for any damages
7 arising from the use of this software.
8
9 Permission is granted to anyone to use this software for any purpose,
10 including commercial applications, and to alter it and redistribute it
11 freely, subject to the following restrictions:
12
13 1. The origin of this software must not be misrepresented; you must not
14 claim that you wrote the original software. If you use this software
15 in a product, an acknowledgment in the product documentation would be
16 appreciated but is not required.
17 2. Altered source versions must be plainly marked as such, and must not be
18 misrepresented as being the original software.
19 3. This notice may not be removed or altered from any source distribution.
20*/
21
22#ifndef SDL_thread_h_
23#define SDL_thread_h_
24
25/**
26 * # CategoryThread
27 *
28 * SDL offers cross-platform thread management functions. These are mostly
29 * concerned with starting threads, setting their priority, and dealing with
30 * their termination.
31 *
32 * In addition, there is support for Thread Local Storage (data that is unique
33 * to each thread, but accessed from a single key).
34 *
35 * On platforms without thread support (such as Emscripten when built without
36 * pthreads), these functions still exist, but things like SDL_CreateThread()
37 * will report failure without doing anything.
38 *
39 * If you're going to work with threads, you almost certainly need to have a
40 * good understanding of [CategoryMutex](CategoryMutex) as well.
41 */
42
43#include <SDL3/SDL_stdinc.h>
44#include <SDL3/SDL_error.h>
45#include <SDL3/SDL_properties.h>
46
47/* Thread synchronization primitives */
48#include <SDL3/SDL_atomic.h>
49
50#if defined(SDL_PLATFORM_WINDOWS)
51#include <process.h> /* _beginthreadex() and _endthreadex() */
52#endif
53
54#include <SDL3/SDL_begin_code.h>
55/* Set up for C function definitions, even when using C++ */
56#ifdef __cplusplus
57extern "C" {
58#endif
59
60/**
61 * The SDL thread object.
62 *
63 * These are opaque data.
64 *
65 * \since This datatype is available since SDL 3.2.0.
66 *
67 * \sa SDL_CreateThread
68 * \sa SDL_WaitThread
69 */
70typedef struct SDL_Thread SDL_Thread;
71
72/**
73 * A unique numeric ID that identifies a thread.
74 *
75 * These are different from SDL_Thread objects, which are generally what an
76 * application will operate on, but having a way to uniquely identify a thread
77 * can be useful at times.
78 *
79 * \since This datatype is available since SDL 3.2.0.
80 *
81 * \sa SDL_GetThreadID
82 * \sa SDL_GetCurrentThreadID
83 */
84typedef Uint64 SDL_ThreadID;
85
86/**
87 * Thread local storage ID.
88 *
89 * 0 is the invalid ID. An app can create these and then set data for these
90 * IDs that is unique to each thread.
91 *
92 * \since This datatype is available since SDL 3.2.0.
93 *
94 * \sa SDL_GetTLS
95 * \sa SDL_SetTLS
96 */
97typedef SDL_AtomicInt SDL_TLSID;
98
99/**
100 * The SDL thread priority.
101 *
102 * SDL will make system changes as necessary in order to apply the thread
103 * priority. Code which attempts to control thread state related to priority
104 * should be aware that calling SDL_SetCurrentThreadPriority may alter such
105 * state. SDL_HINT_THREAD_PRIORITY_POLICY can be used to control aspects of
106 * this behavior.
107 *
108 * \since This enum is available since SDL 3.2.0.
109 */
110typedef enum SDL_ThreadPriority {
111 SDL_THREAD_PRIORITY_LOW,
112 SDL_THREAD_PRIORITY_NORMAL,
113 SDL_THREAD_PRIORITY_HIGH,
114 SDL_THREAD_PRIORITY_TIME_CRITICAL
115} SDL_ThreadPriority;
116
117/**
118 * The SDL thread state.
119 *
120 * The current state of a thread can be checked by calling SDL_GetThreadState.
121 *
122 * \since This enum is available since SDL 3.2.0.
123 *
124 * \sa SDL_GetThreadState
125 */
126typedef enum SDL_ThreadState
127{
128 SDL_THREAD_UNKNOWN, /**< The thread is not valid */
129 SDL_THREAD_ALIVE, /**< The thread is currently running */
130 SDL_THREAD_DETACHED, /**< The thread is detached and can't be waited on */
131 SDL_THREAD_COMPLETE /**< The thread has finished and should be cleaned up with SDL_WaitThread() */
132} SDL_ThreadState;
133
134/**
135 * The function passed to SDL_CreateThread() as the new thread's entry point.
136 *
137 * \param data what was passed as `data` to SDL_CreateThread().
138 * \returns a value that can be reported through SDL_WaitThread().
139 *
140 * \since This datatype is available since SDL 3.2.0.
141 */
142typedef int (SDLCALL *SDL_ThreadFunction) (void *data);
143
144
145#ifdef SDL_WIKI_DOCUMENTATION_SECTION
146
147/*
148 * Note that these aren't the correct function signatures in this block, but
149 * this is what the API reference manual should look like for all intents and
150 * purposes.
151 *
152 * Technical details, not for the wiki (hello, header readers!)...
153 *
154 * On Windows (and maybe other platforms), a program might use a different
155 * C runtime than its libraries. Or, in SDL's case, it might use a C runtime
156 * while SDL uses none at all.
157 *
158 * C runtimes expect to initialize thread-specific details when a new thread
159 * is created, but to do this in SDL_CreateThread would require SDL to know
160 * intimate details about the caller's C runtime, which is not possible.
161 *
162 * So SDL_CreateThread has two extra parameters, which are
163 * hidden at compile time by macros: the C runtime's `_beginthreadex` and
164 * `_endthreadex` entry points. If these are not NULL, they are used to spin
165 * and terminate the new thread; otherwise the standard Win32 `CreateThread`
166 * function is used. When `SDL_CreateThread` is called from a compiler that
167 * needs this C runtime thread init function, macros insert the appropriate
168 * function pointers for SDL_CreateThread's caller (which might be a different
169 * compiler with a different runtime in different calls to SDL_CreateThread!).
170 *
171 * SDL_BeginThreadFunction defaults to `_beginthreadex` on Windows (and NULL
172 * everywhere else), but apps that have extremely specific special needs can
173 * define this to something else and the SDL headers will use it, passing the
174 * app-defined value to SDL_CreateThread calls. Redefine this with caution!
175 *
176 * Platforms that don't need _beginthread stuff (most everything) will fail
177 * SDL_CreateThread with an error if these pointers _aren't_ NULL.
178 *
179 * Unless you are doing something extremely complicated, like perhaps a
180 * language binding, **you should never deal with this directly**. Let SDL's
181 * macros handle this platform-specific detail transparently!
182 */
183
184/**
185 * Create a new thread with a default stack size.
186 *
187 * This is a convenience function, equivalent to calling
188 * SDL_CreateThreadWithProperties with the following properties set:
189 *
190 * - `SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER`: `fn`
191 * - `SDL_PROP_THREAD_CREATE_NAME_STRING`: `name`
192 * - `SDL_PROP_THREAD_CREATE_USERDATA_POINTER`: `data`
193 *
194 * Note that this "function" is actually a macro that calls an internal
195 * function with two extra parameters not listed here; they are hidden through
196 * preprocessor macros and are needed to support various C runtimes at the
197 * point of the function call. Language bindings that aren't using the C
198 * headers will need to deal with this.
199 *
200 * Usually, apps should just call this function the same way on every platform
201 * and let the macros hide the details.
202 *
203 * \param fn the SDL_ThreadFunction function to call in the new thread.
204 * \param name the name of the thread.
205 * \param data a pointer that is passed to `fn`.
206 * \returns an opaque pointer to the new thread object on success, NULL if the
207 * new thread could not be created; call SDL_GetError() for more
208 * information.
209 *
210 * \since This function is available since SDL 3.2.0.
211 *
212 * \sa SDL_CreateThreadWithProperties
213 * \sa SDL_WaitThread
214 */
215extern SDL_DECLSPEC SDL_Thread * SDLCALL SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data);
216
217/**
218 * Create a new thread with with the specified properties.
219 *
220 * These are the supported properties:
221 *
222 * - `SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER`: an SDL_ThreadFunction
223 * value that will be called at the start of the new thread's life.
224 * Required.
225 * - `SDL_PROP_THREAD_CREATE_NAME_STRING`: the name of the new thread, which
226 * might be available to debuggers. Optional, defaults to NULL.
227 * - `SDL_PROP_THREAD_CREATE_USERDATA_POINTER`: an arbitrary app-defined
228 * pointer, which is passed to the entry function on the new thread, as its
229 * only parameter. Optional, defaults to NULL.
230 * - `SDL_PROP_THREAD_CREATE_STACKSIZE_NUMBER`: the size, in bytes, of the new
231 * thread's stack. Optional, defaults to 0 (system-defined default).
232 *
233 * SDL makes an attempt to report `SDL_PROP_THREAD_CREATE_NAME_STRING` to the
234 * system, so that debuggers can display it. Not all platforms support this.
235 *
236 * Thread naming is a little complicated: Most systems have very small limits
237 * for the string length (Haiku has 32 bytes, Linux currently has 16, Visual
238 * C++ 6.0 has _nine_!), and possibly other arbitrary rules. You'll have to
239 * see what happens with your system's debugger. The name should be UTF-8 (but
240 * using the naming limits of C identifiers is a better bet). There are no
241 * requirements for thread naming conventions, so long as the string is
242 * null-terminated UTF-8, but these guidelines are helpful in choosing a name:
243 *
244 * https://stackoverflow.com/questions/149932/naming-conventions-for-threads
245 *
246 * If a system imposes requirements, SDL will try to munge the string for it
247 * (truncate, etc), but the original string contents will be available from
248 * SDL_GetThreadName().
249 *
250 * The size (in bytes) of the new stack can be specified with
251 * `SDL_PROP_THREAD_CREATE_STACKSIZE_NUMBER`. Zero means "use the system
252 * default" which might be wildly different between platforms. x86 Linux
253 * generally defaults to eight megabytes, an embedded device might be a few
254 * kilobytes instead. You generally need to specify a stack that is a multiple
255 * of the system's page size (in many cases, this is 4 kilobytes, but check
256 * your system documentation).
257 *
258 * Note that this "function" is actually a macro that calls an internal
259 * function with two extra parameters not listed here; they are hidden through
260 * preprocessor macros and are needed to support various C runtimes at the
261 * point of the function call. Language bindings that aren't using the C
262 * headers will need to deal with this.
263 *
264 * The actual symbol in SDL is `SDL_CreateThreadWithPropertiesRuntime`, so
265 * there is no symbol clash, but trying to load an SDL shared library and look
266 * for "SDL_CreateThreadWithProperties" will fail.
267 *
268 * Usually, apps should just call this function the same way on every platform
269 * and let the macros hide the details.
270 *
271 * \param props the properties to use.
272 * \returns an opaque pointer to the new thread object on success, NULL if the
273 * new thread could not be created; call SDL_GetError() for more
274 * information.
275 *
276 * \since This function is available since SDL 3.2.0.
277 *
278 * \sa SDL_CreateThread
279 * \sa SDL_WaitThread
280 */
281extern SDL_DECLSPEC SDL_Thread * SDLCALL SDL_CreateThreadWithProperties(SDL_PropertiesID props);
282
283#define SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER "SDL.thread.create.entry_function"
284#define SDL_PROP_THREAD_CREATE_NAME_STRING "SDL.thread.create.name"
285#define SDL_PROP_THREAD_CREATE_USERDATA_POINTER "SDL.thread.create.userdata"
286#define SDL_PROP_THREAD_CREATE_STACKSIZE_NUMBER "SDL.thread.create.stacksize"
287
288/* end wiki documentation for macros that are meant to look like functions. */
289#endif
290
291
292/* The real implementation, hidden from the wiki, so it can show this as real functions that don't have macro magic. */
293#ifndef SDL_WIKI_DOCUMENTATION_SECTION
294# if defined(SDL_PLATFORM_WINDOWS)
295# ifndef SDL_BeginThreadFunction
296# define SDL_BeginThreadFunction _beginthreadex
297# endif
298# ifndef SDL_EndThreadFunction
299# define SDL_EndThreadFunction _endthreadex
300# endif
301# endif
302#endif
303
304/* currently no other platforms than Windows use _beginthreadex/_endthreadex things. */
305#ifndef SDL_WIKI_DOCUMENTATION_SECTION
306# ifndef SDL_BeginThreadFunction
307# define SDL_BeginThreadFunction NULL
308# endif
309#endif
310
311#ifndef SDL_WIKI_DOCUMENTATION_SECTION
312# ifndef SDL_EndThreadFunction
313# define SDL_EndThreadFunction NULL
314# endif
315#endif
316
317#ifndef SDL_WIKI_DOCUMENTATION_SECTION
318/* These are the actual functions exported from SDL! Don't use them directly! Use the SDL_CreateThread and SDL_CreateThreadWithProperties macros! */
319/**
320 * The actual entry point for SDL_CreateThread.
321 *
322 * \param fn the SDL_ThreadFunction function to call in the new thread
323 * \param name the name of the thread
324 * \param data a pointer that is passed to `fn`
325 * \param pfnBeginThread the C runtime's _beginthreadex (or whatnot). Can be NULL.
326 * \param pfnEndThread the C runtime's _endthreadex (or whatnot). Can be NULL.
327 * \returns an opaque pointer to the new thread object on success, NULL if the
328 * new thread could not be created; call SDL_GetError() for more
329 * information.
330 *
331 * \since This function is available since SDL 3.2.0.
332 */
333extern SDL_DECLSPEC SDL_Thread * SDLCALL SDL_CreateThreadRuntime(SDL_ThreadFunction fn, const char *name, void *data, SDL_FunctionPointer pfnBeginThread, SDL_FunctionPointer pfnEndThread);
334
335/**
336 * The actual entry point for SDL_CreateThreadWithProperties.
337 *
338 * \param props the properties to use
339 * \param pfnBeginThread the C runtime's _beginthreadex (or whatnot). Can be NULL.
340 * \param pfnEndThread the C runtime's _endthreadex (or whatnot). Can be NULL.
341 * \returns an opaque pointer to the new thread object on success, NULL if the
342 * new thread could not be created; call SDL_GetError() for more
343 * information.
344 *
345 * \since This function is available since SDL 3.2.0.
346 */
347extern SDL_DECLSPEC SDL_Thread * SDLCALL SDL_CreateThreadWithPropertiesRuntime(SDL_PropertiesID props, SDL_FunctionPointer pfnBeginThread, SDL_FunctionPointer pfnEndThread);
348
349#define SDL_CreateThread(fn, name, data) SDL_CreateThreadRuntime((fn), (name), (data), (SDL_FunctionPointer) (SDL_BeginThreadFunction), (SDL_FunctionPointer) (SDL_EndThreadFunction))
350#define SDL_CreateThreadWithProperties(props) SDL_CreateThreadWithPropertiesRuntime((props), (SDL_FunctionPointer) (SDL_BeginThreadFunction), (SDL_FunctionPointer) (SDL_EndThreadFunction))
351#define SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER "SDL.thread.create.entry_function"
352#define SDL_PROP_THREAD_CREATE_NAME_STRING "SDL.thread.create.name"
353#define SDL_PROP_THREAD_CREATE_USERDATA_POINTER "SDL.thread.create.userdata"
354#define SDL_PROP_THREAD_CREATE_STACKSIZE_NUMBER "SDL.thread.create.stacksize"
355#endif
356
357
358/**
359 * Get the thread name as it was specified in SDL_CreateThread().
360 *
361 * \param thread the thread to query.
362 * \returns a pointer to a UTF-8 string that names the specified thread, or
363 * NULL if it doesn't have a name.
364 *
365 * \since This function is available since SDL 3.2.0.
366 */
367extern SDL_DECLSPEC const char * SDLCALL SDL_GetThreadName(SDL_Thread *thread);
368
369/**
370 * Get the thread identifier for the current thread.
371 *
372 * This thread identifier is as reported by the underlying operating system.
373 * If SDL is running on a platform that does not support threads the return
374 * value will always be zero.
375 *
376 * This function also returns a valid thread ID when called from the main
377 * thread.
378 *
379 * \returns the ID of the current thread.
380 *
381 * \since This function is available since SDL 3.2.0.
382 *
383 * \sa SDL_GetThreadID
384 */
385extern SDL_DECLSPEC SDL_ThreadID SDLCALL SDL_GetCurrentThreadID(void);
386
387/**
388 * Get the thread identifier for the specified thread.
389 *
390 * This thread identifier is as reported by the underlying operating system.
391 * If SDL is running on a platform that does not support threads the return
392 * value will always be zero.
393 *
394 * \param thread the thread to query.
395 * \returns the ID of the specified thread, or the ID of the current thread if
396 * `thread` is NULL.
397 *
398 * \since This function is available since SDL 3.2.0.
399 *
400 * \sa SDL_GetCurrentThreadID
401 */
402extern SDL_DECLSPEC SDL_ThreadID SDLCALL SDL_GetThreadID(SDL_Thread *thread);
403
404/**
405 * Set the priority for the current thread.
406 *
407 * Note that some platforms will not let you alter the priority (or at least,
408 * promote the thread to a higher priority) at all, and some require you to be
409 * an administrator account. Be prepared for this to fail.
410 *
411 * \param priority the SDL_ThreadPriority to set.
412 * \returns true on success or false on failure; call SDL_GetError() for more
413 * information.
414 *
415 * \since This function is available since SDL 3.2.0.
416 */
417extern SDL_DECLSPEC bool SDLCALL SDL_SetCurrentThreadPriority(SDL_ThreadPriority priority);
418
419/**
420 * Wait for a thread to finish.
421 *
422 * Threads that haven't been detached will remain until this function cleans
423 * them up. Not doing so is a resource leak.
424 *
425 * Once a thread has been cleaned up through this function, the SDL_Thread
426 * that references it becomes invalid and should not be referenced again. As
427 * such, only one thread may call SDL_WaitThread() on another.
428 *
429 * The return code from the thread function is placed in the area pointed to
430 * by `status`, if `status` is not NULL.
431 *
432 * You may not wait on a thread that has been used in a call to
433 * SDL_DetachThread(). Use either that function or this one, but not both, or
434 * behavior is undefined.
435 *
436 * It is safe to pass a NULL thread to this function; it is a no-op.
437 *
438 * Note that the thread pointer is freed by this function and is not valid
439 * afterward.
440 *
441 * \param thread the SDL_Thread pointer that was returned from the
442 * SDL_CreateThread() call that started this thread.
443 * \param status a pointer filled in with the value returned from the thread
444 * function by its 'return', or -1 if the thread has been
445 * detached or isn't valid, may be NULL.
446 *
447 * \since This function is available since SDL 3.2.0.
448 *
449 * \sa SDL_CreateThread
450 * \sa SDL_DetachThread
451 */
452extern SDL_DECLSPEC void SDLCALL SDL_WaitThread(SDL_Thread *thread, int *status);
453
454/**
455 * Get the current state of a thread.
456 *
457 * \param thread the thread to query.
458 * \returns the current state of a thread, or SDL_THREAD_UNKNOWN if the thread
459 * isn't valid.
460 *
461 * \since This function is available since SDL 3.2.0.
462 *
463 * \sa SDL_ThreadState
464 */
465extern SDL_DECLSPEC SDL_ThreadState SDLCALL SDL_GetThreadState(SDL_Thread *thread);
466
467/**
468 * Let a thread clean up on exit without intervention.
469 *
470 * A thread may be "detached" to signify that it should not remain until
471 * another thread has called SDL_WaitThread() on it. Detaching a thread is
472 * useful for long-running threads that nothing needs to synchronize with or
473 * further manage. When a detached thread is done, it simply goes away.
474 *
475 * There is no way to recover the return code of a detached thread. If you
476 * need this, don't detach the thread and instead use SDL_WaitThread().
477 *
478 * Once a thread is detached, you should usually assume the SDL_Thread isn't
479 * safe to reference again, as it will become invalid immediately upon the
480 * detached thread's exit, instead of remaining until someone has called
481 * SDL_WaitThread() to finally clean it up. As such, don't detach the same
482 * thread more than once.
483 *
484 * If a thread has already exited when passed to SDL_DetachThread(), it will
485 * stop waiting for a call to SDL_WaitThread() and clean up immediately. It is
486 * not safe to detach a thread that might be used with SDL_WaitThread().
487 *
488 * You may not call SDL_WaitThread() on a thread that has been detached. Use
489 * either that function or this one, but not both, or behavior is undefined.
490 *
491 * It is safe to pass NULL to this function; it is a no-op.
492 *
493 * \param thread the SDL_Thread pointer that was returned from the
494 * SDL_CreateThread() call that started this thread.
495 *
496 * \since This function is available since SDL 3.2.0.
497 *
498 * \sa SDL_CreateThread
499 * \sa SDL_WaitThread
500 */
501extern SDL_DECLSPEC void SDLCALL SDL_DetachThread(SDL_Thread *thread);
502
503/**
504 * Get the current thread's value associated with a thread local storage ID.
505 *
506 * \param id a pointer to the thread local storage ID, may not be NULL.
507 * \returns the value associated with the ID for the current thread or NULL if
508 * no value has been set; call SDL_GetError() for more information.
509 *
510 * \threadsafety It is safe to call this function from any thread.
511 *
512 * \since This function is available since SDL 3.2.0.
513 *
514 * \sa SDL_SetTLS
515 */
516extern SDL_DECLSPEC void * SDLCALL SDL_GetTLS(SDL_TLSID *id);
517
518/**
519 * The callback used to cleanup data passed to SDL_SetTLS.
520 *
521 * This is called when a thread exits, to allow an app to free any resources.
522 *
523 * \param value a pointer previously handed to SDL_SetTLS.
524 *
525 * \since This datatype is available since SDL 3.2.0.
526 *
527 * \sa SDL_SetTLS
528 */
529typedef void (SDLCALL *SDL_TLSDestructorCallback)(void *value);
530
531/**
532 * Set the current thread's value associated with a thread local storage ID.
533 *
534 * If the thread local storage ID is not initialized (the value is 0), a new
535 * ID will be created in a thread-safe way, so all calls using a pointer to
536 * the same ID will refer to the same local storage.
537 *
538 * Note that replacing a value from a previous call to this function on the
539 * same thread does _not_ call the previous value's destructor!
540 *
541 * `destructor` can be NULL; it is assumed that `value` does not need to be
542 * cleaned up if so.
543 *
544 * \param id a pointer to the thread local storage ID, may not be NULL.
545 * \param value the value to associate with the ID for the current thread.
546 * \param destructor a function called when the thread exits, to free the
547 * value, may be NULL.
548 * \returns true on success or false on failure; call SDL_GetError() for more
549 * information.
550 *
551 * \threadsafety It is safe to call this function from any thread.
552 *
553 * \since This function is available since SDL 3.2.0.
554 *
555 * \sa SDL_GetTLS
556 */
557extern SDL_DECLSPEC bool SDLCALL SDL_SetTLS(SDL_TLSID *id, const void *value, SDL_TLSDestructorCallback destructor);
558
559/**
560 * Cleanup all TLS data for this thread.
561 *
562 * If you are creating your threads outside of SDL and then calling SDL
563 * functions, you should call this function before your thread exits, to
564 * properly clean up SDL memory.
565 *
566 * \threadsafety It is safe to call this function from any thread.
567 *
568 * \since This function is available since SDL 3.2.0.
569 */
570extern SDL_DECLSPEC void SDLCALL SDL_CleanupTLS(void);
571
572/* Ends C function definitions when using C++ */
573#ifdef __cplusplus
574}
575#endif
576#include <SDL3/SDL_close_code.h>
577
578#endif /* SDL_thread_h_ */
579