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