Monado OpenXR Runtime
Loading...
Searching...
No Matches
os_threading.h
Go to the documentation of this file.
1// Copyright 2019-2022, Collabora, Ltd.
2// Copyright 2024-2025, NVIDIA CORPORATION.
3// SPDX-License-Identifier: BSL-1.0
4/*!
5 * @file
6 * @brief Wrapper around OS threading native functions.
7 * @author Jakob Bornecrantz <jakob@collabora.com>
8 *
9 * @ingroup aux_os
10 */
11
12#pragma once
13
14#include "xrt/xrt_compiler.h"
15#include "xrt/xrt_config_os.h"
16
17#include "util/u_misc.h"
18
19#include "os/os_time.h"
20
21#if defined(XRT_OS_OSX)
22#include <unistd.h>
23#include <pthread.h>
24#include <assert.h>
25
26#elif defined(XRT_OS_LINUX) || defined(XRT_ENV_MINGW)
27#include <unistd.h>
28#include <pthread.h>
29#include <semaphore.h>
30#include <assert.h>
31#define OS_THREAD_HAVE_SETNAME
32#define OS_THREAD_HAVE_SEMAPHORE
33
34#elif defined(XRT_OS_WINDOWS)
35#include "xrt/xrt_windows.h"
36#include <pthread.h>
37#include <sched.h>
38#include <semaphore.h>
39#include <assert.h>
40#define OS_THREAD_HAVE_SETNAME
41#define OS_THREAD_HAVE_SEMAPHORE
42
43#else
44
45#error "OS not supported"
46
47#endif
48
49#ifdef __cplusplus
50extern "C" {
51#endif
52
53
54/*!
55 * @addtogroup aux_os
56 * @{
57 */
58
59/*
60 *
61 * Mutex
62 *
63 */
64
65/*!
66 * A wrapper around a native mutex.
67 */
69{
70 pthread_mutex_t mutex;
71
72#ifndef NDEBUG
73 bool initialized;
74 bool recursive;
75#endif
76};
77
78/*!
79 * Init.
80 *
81 * @public @memberof os_mutex
82 */
83static inline int
85{
86 assert(!om->initialized);
87#ifndef NDEBUG
88 om->initialized = true;
89 om->recursive = false;
90#endif
91 return pthread_mutex_init(&om->mutex, NULL);
92}
93
94/*!
95 * Lock.
96 *
97 * @public @memberof os_mutex
98 */
99static inline void
101{
102 assert(om->initialized);
103 pthread_mutex_lock(&om->mutex);
104}
105
106/*!
107 * Try to lock, but do not block.
108 *
109 * @public @memberof os_mutex
110 */
111static inline int
113{
114 assert(om->initialized);
115 return pthread_mutex_trylock(&om->mutex);
116}
117
118/*!
119 * Unlock.
120 *
121 * @public @memberof os_mutex
122 */
123static inline void
125{
126 assert(om->initialized);
127 pthread_mutex_unlock(&om->mutex);
128}
129
130/*!
131 * Clean up.
132 *
133 * @public @memberof os_mutex
134 */
135static inline void
137{
138 assert(om->initialized);
139 assert(!om->recursive);
140
141 pthread_mutex_destroy(&om->mutex);
142
143#ifndef NDEBUG
144 om->initialized = false;
145 om->recursive = false;
146#endif
147}
148
149/*!
150 * Init.
151 *
152 * @public @memberof os_mutex
153 */
154static inline int
156{
157 assert(!om->initialized);
158
159#ifndef NDEBUG
160 om->initialized = true;
161 om->recursive = true;
162#endif
163
164 pthread_mutexattr_t attr;
165 pthread_mutexattr_init(&attr);
166 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
167 int ret = pthread_mutex_init(&om->mutex, &attr);
168 pthread_mutexattr_destroy(&attr);
169
170 return ret;
171}
172
173/*!
174 * Clean up.
175 *
176 * @public @memberof os_mutex
177 */
178static inline void
180{
181 assert(om->initialized);
182 assert(om->recursive);
183
184 pthread_mutex_destroy(&om->mutex);
185
186#ifndef NDEBUG
187 om->initialized = false;
188 om->recursive = false;
189#endif
190}
191
192
193/*
194 *
195 * Conditional variable.
196 *
197 */
198
199/*!
200 * A wrapper around a native conditional variable.
201 */
203{
204 pthread_cond_t cond;
205#ifndef NDEBUG
206 bool initialized;
207#endif
208};
209
210/*!
211 * Init.
212 *
213 * @public @memberof os_cond
214 */
215static inline int
217{
218 assert(!oc->initialized);
219#ifndef NDEBUG
220 oc->initialized = true;
221#endif
222 return pthread_cond_init(&oc->cond, NULL);
223}
224
225/*!
226 * Signal.
227 *
228 * @public @memberof os_cond
229 */
230static inline void
232{
233 assert(oc->initialized);
234 pthread_cond_signal(&oc->cond);
235}
236
237/*!
238 * Broadcast (signal to multiple threads).
239 *
240 * @public @memberof os_cond
241 */
242static inline int
244{
245 assert(oc->initialized);
246 return pthread_cond_broadcast(&oc->cond);
247}
248
249/*!
250 * Wait.
251 *
252 * Be sure to call this in a loop, testing some other condition that you
253 * are actually waiting for, as condition variable waits are subject to
254 * spurious wakeups.
255 *
256 * Must be called with the mutex @p om locked.
257 *
258 * Once the wait begins, the mutex @p om is unlocked, to allow another
259 * thread access to change the thing you're monitoring. By the time this
260 * returns, you once again own the lock.
261 *
262 * @public @memberof os_cond
263 */
264static inline void
265os_cond_wait(struct os_cond *oc, struct os_mutex *om)
266{
267 assert(oc->initialized);
268 pthread_cond_wait(&oc->cond, &om->mutex);
269}
270
271/*!
272 * Clean up.
273 *
274 * @public @memberof os_cond
275 */
276static inline void
278{
279 assert(oc->initialized);
280 pthread_cond_destroy(&oc->cond);
281#ifndef NDEBUG
282 oc->initialized = false;
283#endif
284}
285
286
287
288/*
289 *
290 * Thread.
291 *
292 */
293
294/*!
295 * A wrapper around a native thread.
296 */
298{
299 pthread_t thread;
300};
301
302/*!
303 * Run function.
304 *
305 * @public @memberof os_thread
306 */
307typedef void *(*os_run_func_t)(void *);
308
309/*!
310 * Init.
311 *
312 * @public @memberof os_thread
313 */
314static inline int
316{
317 return 0;
318}
319
320/*!
321 * Start thread.
322 *
323 * @public @memberof os_thread
324 */
325static inline int
326os_thread_start(struct os_thread *ost, os_run_func_t func, void *ptr)
327{
328 return pthread_create(&ost->thread, NULL, func, ptr);
329}
330
331/*!
332 * Join.
333 *
334 * @public @memberof os_thread
335 */
336static inline void
338{
339 void *retval;
340
341 pthread_join(ost->thread, &retval);
342 U_ZERO(&ost->thread);
343}
344
345/*!
346 * Destruction.
347 *
348 * @public @memberof os_thread
349 */
350static inline void
352{}
353
354/*!
355 * Gets the number of hardware threads available.
356 */
357static inline int64_t
359{
360#if defined(XRT_OS_LINUX) || defined(XRT_OS_OSX)
361 return (int64_t)sysconf(_SC_NPROCESSORS_ONLN);
362#elif defined(XRT_OS_WINDOWS)
363 SYSTEM_INFO sysinfo = XRT_STRUCT_INIT;
364 GetSystemInfo(&sysinfo);
365 return (int64_t)sysinfo.dwNumberOfProcessors;
366#else
367#error "OS not supported"
368 return -1;
369#endif
370}
371
372/*!
373 * Make a best effort to name the current thread.
374 *
375 * Due to an easy race condition caused by musl starting threads before the
376 * handle is written into memory, only this function is exposed, since
377 * it is the safer option when called by the thread itself.
378 */
379static inline void
380os_thread_name_self(const char *name)
381{
382#ifdef OS_THREAD_HAVE_SETNAME
383 pthread_setname_np(pthread_self(), name);
384#else
385 (void)name;
386#endif
387}
388
389#ifdef OS_THREAD_HAVE_SEMAPHORE
390/*
391 *
392 * Semaphore.
393 *
394 */
395
396/*!
397 * A wrapper around a native semaphore.
398 */
400{
401 sem_t sem;
402};
403
404/*!
405 * Init.
406 *
407 * @public @memberof os_semaphore
408 */
409static inline int
410os_semaphore_init(struct os_semaphore *os, int count)
411{
412 return sem_init(&os->sem, 0, count);
413}
414
415/*!
416 * Release.
417 *
418 * @public @memberof os_semaphore
419 */
420static inline void
422{
423 sem_post(&os->sem);
424}
425
426/*!
427 * Set @p ts to the current time, plus the timeout_ns value.
428 *
429 * Intended for use by the threading code only: the timestamps are not interchangeable with other sources of time.
430 *
431 * @public @memberof os_semaphore
432 */
433static inline int
434os_semaphore_get_realtime_clock(struct timespec *ts, uint64_t timeout_ns)
435{
436#if defined(XRT_OS_WINDOWS) && !defined(XRT_ENV_MINGW)
437 struct timespec relative;
438 os_ns_to_timespec(timeout_ns, &relative);
439 pthread_win32_getabstime_np(ts, &relative);
440 return 0;
441#else
442 struct timespec now;
443 if (clock_gettime(CLOCK_REALTIME, &now) < 0) {
444 assert(false);
445 return -1;
446 }
447 uint64_t now_ns = os_timespec_to_ns(&now);
448 uint64_t when_ns = timeout_ns + now_ns;
449
450 os_ns_to_timespec(when_ns, ts);
451 return 0;
452#endif
453}
454
455/*!
456 * Wait, if @p timeout_ns is zero then waits forever.
457 *
458 * @public @memberof os_semaphore
459 */
460static inline void
461os_semaphore_wait(struct os_semaphore *os, uint64_t timeout_ns)
462{
463 if (timeout_ns == 0) {
464 sem_wait(&os->sem);
465 return;
466 }
467
468 struct timespec abs_timeout;
469 if (os_semaphore_get_realtime_clock(&abs_timeout, timeout_ns) == -1) {
470 assert(false);
471 }
472
473 sem_timedwait(&os->sem, &abs_timeout);
474}
475
476/*!
477 * Clean up.
478 *
479 * @public @memberof os_semaphore
480 */
481static inline void
483{
484 sem_destroy(&os->sem);
485}
486#endif // OS_THREAD_HAVE_SEMAPHORE
487
488
489/*
490 *
491 * Fancy helper.
492 *
493 */
494
495/*!
496 * All in one helper that handles locking, waiting for change and starting a
497 * thread.
498 */
500{
501 pthread_t thread;
502 pthread_mutex_t mutex;
503 pthread_cond_t cond;
504
505 bool initialized;
506 bool running;
507};
508
509/*!
510 * Initialize the thread helper.
511 *
512 * @public @memberof os_thread_helper
513 */
514static inline int
516{
517 U_ZERO(oth);
518
519 int ret = pthread_mutex_init(&oth->mutex, NULL);
520 if (ret != 0) {
521 return ret;
522 }
523
524 ret = pthread_cond_init(&oth->cond, NULL);
525 if (ret) {
526 pthread_mutex_destroy(&oth->mutex);
527 return ret;
528 }
529 oth->initialized = true;
530
531 return 0;
532}
533
534/*!
535 * Start the internal thread.
536 *
537 * @public @memberof os_thread_helper
538 */
539static inline int
540os_thread_helper_start(struct os_thread_helper *oth, os_run_func_t func, void *ptr)
541{
542 pthread_mutex_lock(&oth->mutex);
543
544 assert(oth->initialized);
545 if (oth->running) {
546 pthread_mutex_unlock(&oth->mutex);
547 return -1;
548 }
549
550 int ret = pthread_create(&oth->thread, NULL, func, ptr);
551 if (ret != 0) {
552 pthread_mutex_unlock(&oth->mutex);
553 return ret;
554 }
555
556 oth->running = true;
557
558 pthread_mutex_unlock(&oth->mutex);
559
560 return 0;
561}
562
563/*!
564 * @brief Signal from within the thread that we are stopping.
565 *
566 * Call with mutex unlocked - it takes and releases the lock internally.
567 *
568 * @public @memberof os_thread_helper
569 */
570static inline int
572{
573 // The fields are protected.
574 pthread_mutex_lock(&oth->mutex);
575 assert(oth->initialized);
576
577 // Report we're stopping the thread.
578 oth->running = false;
579
580 // Wake up any waiting thread.
581 pthread_cond_signal(&oth->cond);
582
583 // No longer need to protect fields.
584 pthread_mutex_unlock(&oth->mutex);
585
586 return 0;
587}
588
589/*!
590 * @brief Stop the thread and wait for it to exit.
591 *
592 * Call with mutex unlocked - it takes and releases the lock internally.
593 *
594 * @public @memberof os_thread_helper
595 */
596static inline int
598{
599 void *retval = NULL;
600
601 // The fields are protected.
602 pthread_mutex_lock(&oth->mutex);
603 assert(oth->initialized);
604
605 if (!oth->running) {
606 // it already exited
607 pthread_mutex_unlock(&oth->mutex);
608 return 0;
609 }
610
611 // Stop the thread.
612 oth->running = false;
613
614 // Wake up the thread if it is waiting.
615 pthread_cond_signal(&oth->cond);
616
617 // No longer need to protect fields.
618 pthread_mutex_unlock(&oth->mutex);
619
620 // Wait for thread to finish.
621 pthread_join(oth->thread, &retval);
622
623 return 0;
624}
625
626/*!
627 * Destroy the thread helper, externally synchronizable.
628 *
629 * Integrates a call to @ref os_thread_helper_stop_and_wait, so you may just call this for full cleanup
630 *
631 * @public @memberof os_thread_helper
632 */
633static inline void
635{
636 assert(oth->initialized);
637 // Stop the thread.
638 os_thread_helper_stop_and_wait(oth);
639
640 // Destroy resources.
641 pthread_mutex_destroy(&oth->mutex);
642 pthread_cond_destroy(&oth->cond);
643 oth->initialized = false;
644}
645
646/*!
647 * Lock the helper.
648 *
649 * @public @memberof os_thread_helper
650 */
651static inline void
653{
654 pthread_mutex_lock(&oth->mutex);
655}
656
657/*!
658 * Unlock the helper.
659 *
660 * @public @memberof os_thread_helper
661 */
662static inline void
664{
665 pthread_mutex_unlock(&oth->mutex);
666}
667
668/*!
669 * Is the thread running, or supposed to be running.
670 *
671 * Call with mutex unlocked - it takes and releases the lock internally.
672 * If you already have a lock, use os_thread_helper_is_running_locked().
673 *
674 * @public @memberof os_thread_helper
675 */
676static inline bool
678{
679 os_thread_helper_lock(oth);
680 assert(oth->initialized);
681 bool ret = oth->running;
682 os_thread_helper_unlock(oth);
683 return ret;
684}
685
686/*!
687 * Is the thread running, or supposed to be running.
688 *
689 * Must be called with the helper locked.
690 * If you don't have the helper locked for some other reason already,
691 * you can use os_thread_helper_is_running()
692 *
693 * @public @memberof os_thread_helper
694 */
695static inline bool
697{
698 return oth->running;
699}
700
701/*!
702 * Wait for a signal.
703 *
704 * Be sure to call this in a loop, testing some other condition that you
705 * are actually waiting for, as this is backed by a condition variable
706 * wait and is thus subject to spurious wakeups.
707 *
708 * Must be called with the helper locked.
709 *
710 * As this wraps a cond-var wait, once the wait begins, the helper is
711 * unlocked, to allow another thread access to change the thing you're
712 * monitoring. By the time this returns, you once again own the lock.
713 *
714 * @public @memberof os_thread_helper
715 */
716static inline void
718{
719 pthread_cond_wait(&oth->cond, &oth->mutex);
720}
721
722/*!
723 * Signal a waiting thread to wake up.
724 *
725 * Must be called with the helper locked.
726 *
727 * @public @memberof os_thread_helper
728 */
729static inline void
731{
732 pthread_cond_signal(&oth->cond);
733}
734
735/*!
736 * @}
737 */
738
739
740#ifdef __cplusplus
741} // extern "C"
742#endif
743
744
745#ifdef __cplusplus
746namespace xrt::auxiliary::os {
747
748
749//! A class owning an @ref os_mutex
750class Mutex
751{
752public:
753 //! Construct a mutex
754 Mutex() noexcept
755 {
756 os_mutex_init(&inner_);
757 }
758 //! Destroy a mutex when it goes out of scope
759 ~Mutex()
760 {
761 os_mutex_destroy(&inner_);
762 }
763
764 //! Block until the lock can be taken.
765 void
766 lock() noexcept
767 {
768 os_mutex_lock(&inner_);
769 }
770
771 //! Take the lock and return true if possible, but do not block
772 bool
773 try_lock() noexcept
774 {
775 return 0 == os_mutex_trylock(&inner_);
776 }
777
778 //! Release the lock
779 void
780 unlock() noexcept
781 {
782 os_mutex_unlock(&inner_);
783 }
784
785 //! Get a pointer to the owned mutex: do not delete it!
786 os_mutex *
787 get_inner() noexcept
788 {
789 return &inner_;
790 }
791
792 // Do not copy or delete these mutexes.
793 Mutex(Mutex const &) = delete;
794 Mutex(Mutex &&) = delete;
795 Mutex &
796 operator=(Mutex const &) = delete;
797 Mutex &
798 operator=(Mutex &&) = delete;
799
800private:
801 os_mutex inner_{};
802};
803
804} // namespace xrt::auxiliary::os
805
806#endif // __cplusplus
static int64_t os_timespec_to_ns(const struct timespec *spec)
Convert a timespec struct to nanoseconds.
Definition os_time.h:273
static void os_ns_to_timespec(int64_t ns, struct timespec *spec)
Convert an nanosecond integer to a timespec struct.
Definition os_time.h:282
static void os_mutex_recursive_destroy(struct os_mutex *om)
Clean up.
Definition os_threading.h:179
static bool os_thread_helper_is_running_locked(struct os_thread_helper *oth)
Is the thread running, or supposed to be running.
Definition os_threading.h:696
static int os_cond_broadcast(struct os_cond *oc)
Broadcast (signal to multiple threads).
Definition os_threading.h:243
static int os_thread_helper_start(struct os_thread_helper *oth, os_run_func_t func, void *ptr)
Start the internal thread.
Definition os_threading.h:540
static int os_mutex_init(struct os_mutex *om)
Init.
Definition os_threading.h:84
static int os_semaphore_get_realtime_clock(struct timespec *ts, uint64_t timeout_ns)
Set ts to the current time, plus the timeout_ns value.
Definition os_threading.h:434
static void os_thread_helper_signal_locked(struct os_thread_helper *oth)
Signal a waiting thread to wake up.
Definition os_threading.h:730
static void os_mutex_lock(struct os_mutex *om)
Lock.
Definition os_threading.h:100
static void os_cond_wait(struct os_cond *oc, struct os_mutex *om)
Wait.
Definition os_threading.h:265
static int os_thread_helper_stop_and_wait(struct os_thread_helper *oth)
Stop the thread and wait for it to exit.
Definition os_threading.h:597
static void os_thread_destroy(struct os_thread *ost)
Destruction.
Definition os_threading.h:351
static void os_semaphore_release(struct os_semaphore *os)
Release.
Definition os_threading.h:421
static void os_thread_name_self(const char *name)
Make a best effort to name the current thread.
Definition os_threading.h:380
static void os_thread_join(struct os_thread *ost)
Join.
Definition os_threading.h:337
static int os_thread_start(struct os_thread *ost, os_run_func_t func, void *ptr)
Start thread.
Definition os_threading.h:326
static int os_thread_helper_signal_stop(struct os_thread_helper *oth)
Signal from within the thread that we are stopping.
Definition os_threading.h:571
static int os_mutex_recursive_init(struct os_mutex *om)
Init.
Definition os_threading.h:155
static void os_thread_helper_wait_locked(struct os_thread_helper *oth)
Wait for a signal.
Definition os_threading.h:717
static int os_semaphore_init(struct os_semaphore *os, int count)
Init.
Definition os_threading.h:410
static int os_thread_init(struct os_thread *ost)
Init.
Definition os_threading.h:315
static void os_cond_signal(struct os_cond *oc)
Signal.
Definition os_threading.h:231
static int64_t os_hardware_thread_count(void)
Gets the number of hardware threads available.
Definition os_threading.h:358
static int os_mutex_trylock(struct os_mutex *om)
Try to lock, but do not block.
Definition os_threading.h:112
static void os_thread_helper_unlock(struct os_thread_helper *oth)
Unlock the helper.
Definition os_threading.h:663
static int os_thread_helper_init(struct os_thread_helper *oth)
Initialize the thread helper.
Definition os_threading.h:515
static int os_cond_init(struct os_cond *oc)
Init.
Definition os_threading.h:216
static void os_thread_helper_destroy(struct os_thread_helper *oth)
Destroy the thread helper, externally synchronizable.
Definition os_threading.h:634
static bool os_thread_helper_is_running(struct os_thread_helper *oth)
Is the thread running, or supposed to be running.
Definition os_threading.h:677
static void os_mutex_unlock(struct os_mutex *om)
Unlock.
Definition os_threading.h:124
static void os_mutex_destroy(struct os_mutex *om)
Clean up.
Definition os_threading.h:136
static void os_semaphore_destroy(struct os_semaphore *os)
Clean up.
Definition os_threading.h:482
static void os_thread_helper_lock(struct os_thread_helper *oth)
Lock the helper.
Definition os_threading.h:652
static void os_cond_destroy(struct os_cond *oc)
Clean up.
Definition os_threading.h:277
static void os_semaphore_wait(struct os_semaphore *os, uint64_t timeout_ns)
Wait, if timeout_ns is zero then waits forever.
Definition os_threading.h:461
#define U_ZERO(PTR)
Zeroes the correct amount of memory based on the type pointed-to by the argument.
Definition u_misc.h:68
#define XRT_STRUCT_INIT
Very small default init for structs that works in both C and C++.
Definition xrt_compiler.h:311
Wrapper around OS native time functions.
A wrapper around a native conditional variable.
Definition os_threading.h:203
A wrapper around a native mutex.
Definition os_threading.h:69
A wrapper around a native semaphore.
Definition os_threading.h:400
All in one helper that handles locking, waiting for change and starting a thread.
Definition os_threading.h:500
A wrapper around a native thread.
Definition os_threading.h:298
Definition u_worker.c:38
Very small misc utils.
Header holding common defines.
Auto detect OS and certain features.
A minimal way to include Windows.h.