comparison SDL3/SDL_thread.h @ 1:20d02a178406 default tip

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