GuestHost/installation/VBoxWinDrvInst.cpp: Try harder if DiInstallDriverW() returns...
[vbox.git] / include / iprt / thread.h
blob9a3d42fdf3c1b6ed56882f050e688d8447f29c8d
1 /** @file
2 * IPRT - Threads.
3 */
5 /*
6 * Copyright (C) 2006-2024 Oracle and/or its affiliates.
8 * This file is part of VirtualBox base platform packages, as
9 * available from https://www.virtualbox.org.
11 * This program is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU General Public License
13 * as published by the Free Software Foundation, in version 3 of the
14 * License.
16 * This program is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 * The contents of this file may alternatively be used under the terms
25 * of the Common Development and Distribution License Version 1.0
26 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
27 * in the VirtualBox distribution, in which case the provisions of the
28 * CDDL are applicable instead of those of the GPL.
30 * You may elect to license modified versions of this file under the
31 * terms and conditions of either the GPL or the CDDL or both.
33 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
36 #ifndef IPRT_INCLUDED_thread_h
37 #define IPRT_INCLUDED_thread_h
38 #ifndef RT_WITHOUT_PRAGMA_ONCE
39 # pragma once
40 #endif
42 #include <iprt/cdefs.h>
43 #include <iprt/types.h>
44 #include <iprt/stdarg.h>
47 RT_C_DECLS_BEGIN
49 /** @defgroup grp_rt_thread RTThread - Thread Management
50 * @ingroup grp_rt
51 * @{
54 /**
55 * The thread state.
57 typedef enum RTTHREADSTATE
59 /** The usual invalid 0 value. */
60 RTTHREADSTATE_INVALID = 0,
61 /** The thread is being initialized. */
62 RTTHREADSTATE_INITIALIZING,
63 /** The thread has terminated */
64 RTTHREADSTATE_TERMINATED,
65 /** Probably running. */
66 RTTHREADSTATE_RUNNING,
68 /** Waiting on a critical section. */
69 RTTHREADSTATE_CRITSECT,
70 /** Waiting on a event semaphore. */
71 RTTHREADSTATE_EVENT,
72 /** Waiting on a event multiple wakeup semaphore. */
73 RTTHREADSTATE_EVENT_MULTI,
74 /** Waiting on a fast mutex. */
75 RTTHREADSTATE_FAST_MUTEX,
76 /** Waiting on a mutex. */
77 RTTHREADSTATE_MUTEX,
78 /** Waiting on a read write semaphore, read (shared) access. */
79 RTTHREADSTATE_RW_READ,
80 /** Waiting on a read write semaphore, write (exclusive) access. */
81 RTTHREADSTATE_RW_WRITE,
82 /** The thread is sleeping. */
83 RTTHREADSTATE_SLEEP,
84 /** Waiting on a spin mutex. */
85 RTTHREADSTATE_SPIN_MUTEX,
86 /** End of the thread states. */
87 RTTHREADSTATE_END,
89 /** The usual 32-bit size hack. */
90 RTTHREADSTATE_32BIT_HACK = 0x7fffffff
91 } RTTHREADSTATE;
93 /** Checks if a thread state indicates that the thread is sleeping. */
94 #define RTTHREAD_IS_SLEEPING(enmState) ((enmState) >= RTTHREADSTATE_CRITSECT)
96 /**
97 * Thread types.
98 * Besides identifying the purpose of the thread, the thread type is
99 * used to select the scheduling properties.
101 * The types in are placed in a rough order of ascending priority.
103 typedef enum RTTHREADTYPE
105 /** Invalid type. */
106 RTTHREADTYPE_INVALID = 0,
107 /** Infrequent poller thread.
108 * This type of thread will sleep for the most of the time, and do
109 * infrequent polls on resources at 0.5 sec or higher intervals.
111 RTTHREADTYPE_INFREQUENT_POLLER,
112 /** Main heavy worker thread.
113 * Thread of this type is driving asynchronous tasks in the Main
114 * API which takes a long time and might involve a bit of CPU. Like
115 * for instance creating a fixed sized VDI.
117 RTTHREADTYPE_MAIN_HEAVY_WORKER,
118 /** The emulation thread type.
119 * While being a thread with very high workload it still is vital
120 * that it gets scheduled frequently. When possible all other thread
121 * types except DEFAULT and GUI should interrupt this one ASAP when
122 * they become ready.
124 RTTHREADTYPE_EMULATION,
125 /** The default thread type.
126 * Since it doesn't say much about the purpose of the thread
127 * nothing special is normally done to the scheduling. This type
128 * should be avoided.
129 * The main thread is registered with default type during RTR3Init()
130 * and that's what the default process priority is derived from.
132 RTTHREADTYPE_DEFAULT,
133 /** The GUI thread type
134 * The GUI normally have a low workload but is frequently scheduled
135 * to handle events. When possible the scheduler should not leave
136 * threads of this kind waiting for too long (~50ms).
138 RTTHREADTYPE_GUI,
139 /** Main worker thread.
140 * Thread of this type is driving asynchronous tasks in the Main API.
141 * In most cases this means little work an a lot of waiting.
143 RTTHREADTYPE_MAIN_WORKER,
144 /** VRDP I/O thread.
145 * These threads are I/O threads in the RDP server will hang around
146 * waiting for data, process it and pass it on.
148 RTTHREADTYPE_VRDP_IO,
149 /** The debugger type.
150 * Threads involved in servicing the debugger. It must remain
151 * responsive even when things are running wild in.
153 RTTHREADTYPE_DEBUGGER,
154 /** Message pump thread.
155 * Thread pumping messages from one thread/process to another
156 * thread/process. The workload is very small, most of the time
157 * it's blocked waiting for messages to be produced or processed.
158 * This type of thread will be favored after I/O threads.
160 RTTHREADTYPE_MSG_PUMP,
161 /** The I/O thread type.
162 * Doing I/O means shuffling data, waiting for request to arrive and
163 * for them to complete. The thread should be favored when competing
164 * with any other threads except timer threads.
166 RTTHREADTYPE_IO,
167 /** The timer thread type.
168 * A timer thread is mostly waiting for the timer to tick
169 * and then perform a little bit of work. Accuracy is important here,
170 * so the thread should be favoured over all threads. If premention can
171 * be configured at thread level, it could be made very short.
173 RTTHREADTYPE_TIMER,
174 /** Only used for validation. */
175 RTTHREADTYPE_END
176 } RTTHREADTYPE;
179 #if !defined(IN_RC) || defined(DOXYGEN_RUNNING)
182 * Checks if the IPRT thread component has been initialized.
184 * This is used to avoid calling into RTThread before the runtime has been
185 * initialized.
187 * @returns @c true if it's initialized, @c false if not.
189 RTDECL(bool) RTThreadIsInitialized(void);
192 * Get the thread handle of the current thread.
194 * @returns Thread handle.
196 RTDECL(RTTHREAD) RTThreadSelf(void);
199 * Get the native thread handle of the current thread.
201 * @returns Native thread handle.
203 RTDECL(RTNATIVETHREAD) RTThreadNativeSelf(void);
206 * Millisecond granular sleep function.
208 * @returns VINF_SUCCESS on success.
209 * @returns VERR_INTERRUPTED if a signal or other asynchronous stuff happened
210 * which interrupt the peaceful sleep.
211 * @param cMillies Number of milliseconds to sleep.
212 * 0 milliseconds means yielding the timeslice - deprecated!
213 * @remark See RTThreadNanoSleep() for sleeping for smaller periods of time.
215 RTDECL(int) RTThreadSleep(RTMSINTERVAL cMillies);
218 * Millisecond granular sleep function, no logger calls.
220 * Same as RTThreadSleep, except it will never call into the IPRT logger. It
221 * can therefore safely be used in places where the logger is off limits, like
222 * at termination or init time. The electric fence heap is one consumer of
223 * this API.
225 * @returns VINF_SUCCESS on success.
226 * @returns VERR_INTERRUPTED if a signal or other asynchronous stuff happened
227 * which interrupt the peaceful sleep.
228 * @param cMillies Number of milliseconds to sleep.
229 * 0 milliseconds means yielding the timeslice - deprecated!
231 RTDECL(int) RTThreadSleepNoLog(RTMSINTERVAL cMillies);
234 * Yields the CPU.
236 * @returns true if we yielded.
237 * @returns false if it's probable that we didn't yield.
239 RTDECL(bool) RTThreadYield(void);
244 * Thread function.
246 * @returns 0 on success.
247 * @param ThreadSelf Thread handle to this thread.
248 * @param pvUser User argument.
250 typedef DECLCALLBACKTYPE(int, FNRTTHREAD,(RTTHREAD ThreadSelf, void *pvUser));
251 /** Pointer to a FNRTTHREAD(). */
252 typedef FNRTTHREAD *PFNRTTHREAD;
255 * Thread creation flags.
257 typedef enum RTTHREADFLAGS
259 /** This flag is used to keep the thread structure around so it can
260 * be waited on after termination. @sa RTThreadWait and
261 * RTThreadWaitNoResume. Not required for RTThreadUserWait and friends!
263 RTTHREADFLAGS_WAITABLE = RT_BIT(0),
264 /** The bit number corresponding to the RTTHREADFLAGS_WAITABLE mask. */
265 RTTHREADFLAGS_WAITABLE_BIT = 0,
267 /** Call CoInitializeEx w/ COINIT_MULTITHREADED, COINIT_DISABLE_OLE1DDE and
268 * COINIT_SPEED_OVER_MEMORY. Ignored on non-windows platforms. */
269 RTTHREADFLAGS_COM_MTA = RT_BIT(1),
270 /** Call CoInitializeEx w/ COINIT_APARTMENTTHREADED and
271 * COINIT_SPEED_OVER_MEMORY. Ignored on non-windows platforms. */
272 RTTHREADFLAGS_COM_STA = RT_BIT(2),
274 /** Mask all signals that we can mask. Ignored on most non-posix platforms.
275 * @note RTThreadPoke() will not necessarily work for a thread create with
276 * this flag. */
277 RTTHREADFLAGS_NO_SIGNALS = RT_BIT(3),
279 /** Mask of valid flags, use for validation. */
280 RTTHREADFLAGS_MASK = UINT32_C(0xf)
281 } RTTHREADFLAGS;
283 /** Max thread name length (including zero terminator). */
284 #define RTTHREAD_NAME_LEN 16
287 * Create a new thread.
289 * @returns iprt status code.
290 * @param pThread Where to store the thread handle to the new thread. (optional)
291 * @param pfnThread The thread function.
292 * @param pvUser User argument.
293 * @param cbStack The size of the stack for the new thread.
294 * Use 0 for the default stack size.
295 * @param enmType The thread type. Used for deciding scheduling attributes
296 * of the thread.
297 * @param fFlags Flags of the RTTHREADFLAGS type (ORed together).
298 * @param pszName Thread name.
300 * @remark When called in Ring-0, this API will create a new kernel thread and not a thread in
301 * the context of the calling process.
303 RTDECL(int) RTThreadCreate(PRTTHREAD pThread, PFNRTTHREAD pfnThread, void *pvUser, size_t cbStack,
304 RTTHREADTYPE enmType, unsigned fFlags, const char *pszName);
305 #ifndef RT_OS_LINUX /* XXX crashes genksyms at least on 32-bit Linux hosts */
306 /** Pointer to a RTThreadCreate function. */
307 typedef DECLCALLBACKPTR(int, PFNRTTHREADCREATE,(PRTTHREAD pThread, PFNRTTHREAD pfnThread, void *pvUser, size_t cbStack,
308 RTTHREADTYPE enmType, unsigned fFlags, const char *pszName));
309 #endif
313 * Create a new thread.
315 * Same as RTThreadCreate except the name is given in the RTStrPrintfV form.
317 * @returns iprt status code.
318 * @param pThread See RTThreadCreate.
319 * @param pfnThread See RTThreadCreate.
320 * @param pvUser See RTThreadCreate.
321 * @param cbStack See RTThreadCreate.
322 * @param enmType See RTThreadCreate.
323 * @param fFlags See RTThreadCreate.
324 * @param pszNameFmt Thread name format.
325 * @param va Format arguments.
327 RTDECL(int) RTThreadCreateV(PRTTHREAD pThread, PFNRTTHREAD pfnThread, void *pvUser, size_t cbStack,
328 RTTHREADTYPE enmType, uint32_t fFlags, const char *pszNameFmt, va_list va) RT_IPRT_FORMAT_ATTR(7, 0);
331 * Create a new thread.
333 * Same as RTThreadCreate except the name is given in the RTStrPrintf form.
335 * @returns iprt status code.
336 * @param pThread See RTThreadCreate.
337 * @param pfnThread See RTThreadCreate.
338 * @param pvUser See RTThreadCreate.
339 * @param cbStack See RTThreadCreate.
340 * @param enmType See RTThreadCreate.
341 * @param fFlags See RTThreadCreate.
342 * @param pszNameFmt Thread name format.
343 * @param ... Format arguments.
345 RTDECL(int) RTThreadCreateF(PRTTHREAD pThread, PFNRTTHREAD pfnThread, void *pvUser, size_t cbStack,
346 RTTHREADTYPE enmType, uint32_t fFlags, const char *pszNameFmt, ...) RT_IPRT_FORMAT_ATTR(7, 8);
349 * Gets the native thread id of a IPRT thread.
351 * @returns The native thread id.
352 * @param Thread The IPRT thread.
354 RTDECL(RTNATIVETHREAD) RTThreadGetNative(RTTHREAD Thread);
357 * Gets the native thread handle for a IPRT thread.
359 * @returns The thread handle. INVALID_HANDLE_VALUE on failure.
360 * @param hThread The IPRT thread handle.
362 * @note Windows only.
363 * @note Only valid after parent returns from the thread creation call.
365 RTDECL(uintptr_t) RTThreadGetNativeHandle(RTTHREAD hThread);
368 * Gets the IPRT thread of a native thread.
370 * @returns The IPRT thread handle
371 * @returns NIL_RTTHREAD if not a thread known to IPRT.
372 * @param NativeThread The native thread handle/id.
374 RTDECL(RTTHREAD) RTThreadFromNative(RTNATIVETHREAD NativeThread);
377 * Changes the type of the specified thread.
379 * @returns iprt status code.
380 * @param Thread The thread which type should be changed.
381 * @param enmType The new thread type.
382 * @remark In Ring-0 it only works if Thread == RTThreadSelf().
384 RTDECL(int) RTThreadSetType(RTTHREAD Thread, RTTHREADTYPE enmType);
387 * Wait for the thread to terminate, resume on interruption.
389 * @returns iprt status code.
390 * Will not return VERR_INTERRUPTED.
391 * @param Thread The thread to wait for.
392 * @param cMillies The number of milliseconds to wait. Use RT_INDEFINITE_WAIT for
393 * an indefinite wait.
394 * @param prc Where to store the return code of the thread. Optional.
396 RTDECL(int) RTThreadWait(RTTHREAD Thread, RTMSINTERVAL cMillies, int *prc);
399 * Wait for the thread to terminate, return on interruption.
401 * @returns iprt status code.
402 * @param Thread The thread to wait for.
403 * @param cMillies The number of milliseconds to wait. Use RT_INDEFINITE_WAIT for
404 * an indefinite wait.
405 * @param prc Where to store the return code of the thread. Optional.
407 RTDECL(int) RTThreadWaitNoResume(RTTHREAD Thread, RTMSINTERVAL cMillies, int *prc);
410 * Gets the name of the current thread thread.
412 * @returns Pointer to readonly name string.
413 * @returns NULL on failure.
415 RTDECL(const char *) RTThreadSelfName(void);
418 * Gets the name of a thread.
420 * @returns Pointer to readonly name string.
421 * @returns NULL on failure.
422 * @param Thread Thread handle of the thread to query the name of.
424 RTDECL(const char *) RTThreadGetName(RTTHREAD Thread);
427 * Gets the type of the specified thread.
429 * @returns The thread type.
430 * @returns RTTHREADTYPE_INVALID if the thread handle is invalid.
431 * @param Thread The thread in question.
433 RTDECL(RTTHREADTYPE) RTThreadGetType(RTTHREAD Thread);
436 * Sets the name of a thread.
438 * @returns iprt status code.
439 * @param Thread Thread handle of the thread to query the name of.
440 * @param pszName The thread name.
442 RTDECL(int) RTThreadSetName(RTTHREAD Thread, const char *pszName);
445 * Checks if the specified thread is the main thread.
447 * @returns true if it is, false if it isn't.
449 * @param hThread The thread handle.
451 RTDECL(bool) RTThreadIsMain(RTTHREAD hThread);
454 * Checks if the calling thread is known to IPRT.
456 * @returns @c true if it is, @c false if it isn't.
458 RTDECL(bool) RTThreadIsSelfKnown(void);
461 * Checks if the calling thread is know to IPRT and is alive.
463 * @returns @c true if it is, @c false if it isn't.
465 RTDECL(bool) RTThreadIsSelfAlive(void);
467 #ifdef IN_RING0
469 * Checks whether the specified thread is terminating.
471 * @retval VINF_SUCCESS if not terminating.
472 * @retval VINF_THREAD_IS_TERMINATING if terminating.
473 * @retval VERR_INVALID_HANDLE if hThread is not NIL_RTTHREAD.
474 * @retval VERR_NOT_SUPPORTED if the OS doesn't provide ways to check.
476 * @param hThread The thread to query about, NIL_RTTHREAD is an alias for
477 * the calling thread. Must be NIL_RTTHREAD for now.
479 * @note Not suppored on all OSes, so check for VERR_NOT_SUPPORTED.
481 RTDECL(int) RTThreadQueryTerminationStatus(RTTHREAD hThread);
482 #endif
485 * Signal the user event.
487 * @returns iprt status code.
489 RTDECL(int) RTThreadUserSignal(RTTHREAD Thread);
492 * Wait for the user event.
494 * @returns iprt status code.
495 * @param Thread The thread to wait for.
496 * @param cMillies The number of milliseconds to wait. Use RT_INDEFINITE_WAIT for
497 * an indefinite wait.
499 RTDECL(int) RTThreadUserWait(RTTHREAD Thread, RTMSINTERVAL cMillies);
502 * Wait for the user event, return on interruption.
504 * @returns iprt status code.
505 * @param Thread The thread to wait for.
506 * @param cMillies The number of milliseconds to wait. Use RT_INDEFINITE_WAIT for
507 * an indefinite wait.
509 RTDECL(int) RTThreadUserWaitNoResume(RTTHREAD Thread, RTMSINTERVAL cMillies);
512 * Reset the user event.
514 * @returns iprt status code.
515 * @param Thread The thread to reset.
517 RTDECL(int) RTThreadUserReset(RTTHREAD Thread);
520 * Pokes the thread.
522 * This will wake up or/and signal the thread, attempting to interrupt whatever
523 * it's currently doing.
525 * The posixy version of this will send a signal to the thread, quite likely
526 * waking it up from normal sleeps, waits, and I/O. When IPRT is in
527 * non-obtrusive mode, the posixy version will definitely return
528 * VERR_NOT_IMPLEMENTED, and it may also do so if no usable signal was found.
530 * On Windows the thread will be alerted, waking it up from most sleeps and
531 * waits, but not probably very little in the I/O area (needs testing). On NT
532 * 3.50 and 3.1 VERR_NOT_IMPLEMENTED will be returned.
534 * @returns IPRT status code.
536 * @param hThread The thread to poke. This must not be the
537 * calling thread.
539 * @note This is *NOT* implemented on all platforms and may cause unresolved
540 * symbols during linking or VERR_NOT_IMPLEMENTED at runtime.
543 RTDECL(int) RTThreadPoke(RTTHREAD hThread);
546 * Controls the masking of the signal used by RTThreadPoke on posix systems.
548 * This function is not available on non-posix systems.
550 * @returns IPRT status code.
552 * @param hThread The current thread.
553 * @param fEnable Whether to enable poking (unblock) or to disable it
554 * (block the signal).
556 RTDECL(int) RTThreadControlPokeSignal(RTTHREAD hThread, bool fEnable);
559 # ifdef IN_RING0
562 * Check if preemption is currently enabled or not for the current thread.
564 * @note This may return true even on systems where preemption isn't
565 * possible. In that case, it means no call to RTThreadPreemptDisable
566 * has been made and interrupts are still enabled.
568 * @returns true if preemption is enabled, false if preemetion is disabled.
569 * @param hThread Must be NIL_RTTHREAD for now.
571 RTDECL(bool) RTThreadPreemptIsEnabled(RTTHREAD hThread);
574 * Check if preemption is pending for the current thread.
576 * This function should be called regularly when executing larger portions of
577 * code with preemption disabled.
579 * @returns true if pending, false if not.
580 * @param hThread Must be NIL_RTTHREAD for now.
582 * @note If called with interrupts disabled, the NT kernel may temporarily
583 * re-enable them while checking.
585 RTDECL(bool) RTThreadPreemptIsPending(RTTHREAD hThread);
588 * Is RTThreadPreemptIsPending reliable?
590 * @returns true if reliable, false if not.
592 RTDECL(bool) RTThreadPreemptIsPendingTrusty(void);
595 * Is preemption possible on this system.
597 * @returns true if possible, false if not.
599 RTDECL(bool) RTThreadPreemptIsPossible(void);
602 * Preemption state saved by RTThreadPreemptDisable and used by
603 * RTThreadPreemptRestore to restore the previous state.
605 typedef struct RTTHREADPREEMPTSTATE
607 /** In debug builds this will be used to check for cpu migration. */
608 RTCPUID idCpu;
609 # ifdef RT_OS_WINDOWS
610 /** The old IRQL. Don't touch! */
611 unsigned char uchOldIrql;
612 /** Reserved, MBZ. */
613 uint8_t bReserved1;
614 /** Reserved, MBZ. */
615 uint8_t bReserved2;
616 /** Reserved, MBZ. */
617 uint8_t bReserved3;
618 # define RTTHREADPREEMPTSTATE_INITIALIZER { NIL_RTCPUID, 255, 0, 0, 0 }
619 # elif defined(RT_OS_HAIKU)
620 /** The cpu_state. Don't touch! */
621 uint32_t uOldCpuState;
622 # define RTTHREADPREEMPTSTATE_INITIALIZER { NIL_RTCPUID, 0 }
623 # elif defined(RT_OS_SOLARIS)
624 /** The Old PIL. Don't touch! */
625 uint32_t uOldPil;
626 # define RTTHREADPREEMPTSTATE_INITIALIZER { NIL_RTCPUID, UINT32_MAX }
627 # else
628 /** Reserved, MBZ. */
629 uint32_t u32Reserved;
630 # define RTTHREADPREEMPTSTATE_INITIALIZER { NIL_RTCPUID, 0 }
631 # endif
632 } RTTHREADPREEMPTSTATE;
633 /** Pointer to a preemption state. */
634 typedef RTTHREADPREEMPTSTATE *PRTTHREADPREEMPTSTATE;
637 * Disable preemption.
639 * A call to this function must be matched by exactly one call to
640 * RTThreadPreemptRestore().
642 * @param pState Where to store the preemption state.
644 RTDECL(void) RTThreadPreemptDisable(PRTTHREADPREEMPTSTATE pState);
647 * Restores the preemption state, undoing a previous call to
648 * RTThreadPreemptDisable.
650 * A call to this function must be matching a previous call to
651 * RTThreadPreemptDisable.
653 * @param pState The state return by RTThreadPreemptDisable.
655 RTDECL(void) RTThreadPreemptRestore(PRTTHREADPREEMPTSTATE pState);
658 * Check if the thread is executing in interrupt context.
660 * @returns true if in interrupt context, false if not.
661 * @param hThread Must be NIL_RTTHREAD for now.
663 RTDECL(bool) RTThreadIsInInterrupt(RTTHREAD hThread);
667 * Thread context swithcing events.
669 typedef enum RTTHREADCTXEVENT
671 /** This thread is being scheduled out on the current CPU (includes preemption,
672 * waiting, sleep and whatever else may trigger scheduling). */
673 RTTHREADCTXEVENT_OUT = 0,
674 /** This thread is being scheduled in on the current CPU and will resume
675 * execution. */
676 RTTHREADCTXEVENT_IN,
677 /** The usual 32-bit size hack. */
678 RTTHREADCTXEVENT_32BIT_HACK = 0x7fffffff
679 } RTTHREADCTXEVENT;
682 * Thread context switching hook callback.
684 * This hook function is called when a thread is scheduled and preempted. Check
685 * @a enmEvent to see which it is. Since the function is being called from
686 * hooks inside the scheduler, it is limited what you can do from this function.
687 * Do NOT acquire locks, sleep or yield the thread for instance. IRQ safe
688 * spinlocks are fine though.
690 * @param enmEvent The thread-context event. Please quitely ignore unknown
691 * events, we may add more (thread exit, ++) later.
692 * @param pvUser User argument.
694 typedef DECLCALLBACKTYPE(void, FNRTTHREADCTXHOOK,(RTTHREADCTXEVENT enmEvent, void *pvUser));
695 /** Pointer to a context switching hook. */
696 typedef FNRTTHREADCTXHOOK *PFNRTTHREADCTXHOOK;
699 * Initializes a thread context switching hook for the current thread.
701 * The hook is created as disabled, use RTThreadCtxHookEnable to enable it.
703 * @returns IPRT status code.
704 * @param phCtxHook Where to store the hook handle.
705 * @param fFlags Reserved for future extensions, must be zero.
706 * @param pfnCallback Pointer to a the hook function (callback) that
707 * should be called for all context switching events
708 * involving the current thread.
709 * @param pvUser User argument that will be passed to @a pfnCallback.
710 * @remarks Preemption must be enabled.
712 RTDECL(int) RTThreadCtxHookCreate(PRTTHREADCTXHOOK phCtxHook, uint32_t fFlags, PFNRTTHREADCTXHOOK pfnCallback, void *pvUser);
715 * Destroys a thread context switching hook.
717 * Caller must make sure the hook is disabled before the final reference is
718 * released. Recommended to call this on the owning thread, otherwise the
719 * memory backing it may on some systems only be released when the thread
720 * terminates.
722 * @returns IPRT status code.
724 * @param hCtxHook The context hook handle. NIL_RTTHREADCTXHOOK is
725 * ignored and the function will return VINF_SUCCESS.
726 * @remarks Preemption must be enabled.
727 * @remarks Do not call from FNRTTHREADCTXHOOK.
729 RTDECL(int) RTThreadCtxHookDestroy(RTTHREADCTXHOOK hCtxHook);
732 * Enables the context switching hooks for the current thread.
734 * @returns IPRT status code.
735 * @param hCtxHook The context hook handle.
736 * @remarks Should be called with preemption disabled.
738 RTDECL(int) RTThreadCtxHookEnable(RTTHREADCTXHOOK hCtxHook);
741 * Disables the thread context switching hook for the current thread.
743 * Will not assert or fail if called twice or with a NIL handle.
745 * @returns IPRT status code.
746 * @param hCtxHook The context hook handle. NIL_RTTHREADCTXHOOK is
747 * ignored and the function wil return VINF_SUCCESS.
748 * @remarks Should be called with preemption disabled.
749 * @remarks Do not call from FNRTTHREADCTXHOOK.
751 RTDECL(int) RTThreadCtxHookDisable(RTTHREADCTXHOOK hCtxHook);
754 * Is the thread context switching hook enabled?
756 * @returns true if registered, false if not supported or not registered.
757 * @param hCtxHook The context hook handle. NIL_RTTHREADCTXHOOK is
758 * ignored and the function will return false.
760 * @remarks Can be called from any thread, though is naturally subject to races
761 * when not called from the thread associated with the hook.
763 RTDECL(bool) RTThreadCtxHookIsEnabled(RTTHREADCTXHOOK hCtxHook);
765 # endif /* IN_RING0 */
768 # ifdef IN_RING3
771 * Adopts a non-IPRT thread.
773 * @returns IPRT status code.
774 * @param enmType The thread type.
775 * @param fFlags The thread flags. RTTHREADFLAGS_WAITABLE is not currently allowed.
776 * @param pszName The thread name. Optional
777 * @param pThread Where to store the thread handle. Optional.
779 RTDECL(int) RTThreadAdopt(RTTHREADTYPE enmType, unsigned fFlags, const char *pszName, PRTTHREAD pThread);
782 * Get the thread handle of the current thread, automatically adopting alien
783 * threads.
785 * @returns Thread handle.
787 RTDECL(RTTHREAD) RTThreadSelfAutoAdopt(void);
790 * Gets the affinity mask of the current thread.
792 * @returns IPRT status code.
793 * @param pCpuSet Where to return the CPU affienty set of the calling
794 * thread.
796 RTR3DECL(int) RTThreadGetAffinity(PRTCPUSET pCpuSet);
799 * Sets the affinity mask of the current thread.
801 * @returns iprt status code.
802 * @param pCpuSet The set of CPUs this thread can run on. NULL means
803 * all CPUs.
805 RTR3DECL(int) RTThreadSetAffinity(PCRTCPUSET pCpuSet);
808 * Binds the thread to one specific CPU.
810 * @returns iprt status code.
811 * @param idCpu The ID of the CPU to bind this thread to. Use
812 * NIL_RTCPUID to unbind it.
814 RTR3DECL(int) RTThreadSetAffinityToCpu(RTCPUID idCpu);
817 * Unblocks a thread.
819 * This function is paired with RTThreadBlocking and RTThreadBlockingDebug.
821 * @param hThread The current thread.
822 * @param enmCurState The current state, used to check for nested blocking.
823 * The new state will be running.
825 RTDECL(void) RTThreadUnblocked(RTTHREAD hThread, RTTHREADSTATE enmCurState);
828 * Change the thread state to blocking.
830 * @param hThread The current thread.
831 * @param enmState The sleep state.
832 * @param fReallySleeping Really going to sleep now. Use false before calls
833 * to other IPRT synchronization methods.
835 RTDECL(void) RTThreadBlocking(RTTHREAD hThread, RTTHREADSTATE enmState, bool fReallySleeping);
838 * Get the current thread state.
840 * A thread that is reported as sleeping may actually still be running inside
841 * the lock validator or/and in the code of some other IPRT synchronization
842 * primitive. Use RTThreadGetReallySleeping
844 * @returns The thread state.
845 * @param hThread The thread.
847 RTDECL(RTTHREADSTATE) RTThreadGetState(RTTHREAD hThread);
850 * Checks if the thread is really sleeping or not.
852 * @returns RTTHREADSTATE_RUNNING if not really sleeping, otherwise the state it
853 * is sleeping in.
854 * @param hThread The thread.
856 RTDECL(RTTHREADSTATE) RTThreadGetReallySleeping(RTTHREAD hThread);
859 * Translate a thread state into a string.
861 * @returns Pointer to a read-only string containing the state name.
862 * @param enmState The state.
864 RTDECL(const char *) RTThreadStateName(RTTHREADSTATE enmState);
867 * Native thread states returned by RTThreadNativeState.
869 typedef enum RTTHREADNATIVESTATE
871 /** Invalid thread handle. */
872 RTTHREADNATIVESTATE_INVALID = 0,
873 /** Unable to determine the thread state. */
874 RTTHREADNATIVESTATE_UNKNOWN,
875 /** The thread is running. */
876 RTTHREADNATIVESTATE_RUNNING,
877 /** The thread is blocked. */
878 RTTHREADNATIVESTATE_BLOCKED,
879 /** The thread is suspended / stopped. */
880 RTTHREADNATIVESTATE_SUSPENDED,
881 /** The thread has terminated. */
882 RTTHREADNATIVESTATE_TERMINATED,
883 /** Make sure it's a 32-bit type. */
884 RTTHREADNATIVESTATE_32BIT_HACK = 0x7fffffff
885 } RTTHREADNATIVESTATE;
888 * Get the native state of a thread.
890 * @returns Native state.
891 * @param hThread The thread handle.
893 * @remarks Not yet implemented on all systems, so have a backup plan for
894 * RTTHREADNATIVESTATE_UNKNOWN.
896 RTDECL(RTTHREADNATIVESTATE) RTThreadGetNativeState(RTTHREAD hThread);
899 * Get the execution times of the calling thread.
901 * @returns IPRT status code.
902 * @retval VERR_NOT_IMPLEMENTED if not implemented/supported.
904 * @param[out] pcMsKernelTime Kernel execution time in ms (out).
905 * @param[out] pcMsUserTime User execution time in ms (out).
907 * @remarks Linux and FreeBSD is currently reporting both kernel and user time
908 * together via @a *pcMsUserTime and @a *pcMsKernelTime will always be
909 * set to zero.
911 RTR3DECL(int) RTThreadGetExecutionTimeMilli(uint64_t *pcMsKernelTime, uint64_t *pcMsUserTime);
914 /** @name Thread Local Storage
915 * @{
918 * Thread termination callback for destroying a non-zero TLS entry.
920 * @remarks It is not permitable to use any RTTls APIs at this time. Doing so
921 * may lead to endless loops, crashes, and other bad stuff.
923 * @param pvValue The current value.
925 typedef DECLCALLBACKTYPE(void, FNRTTLSDTOR,(void *pvValue));
926 /** Pointer to a FNRTTLSDTOR. */
927 typedef FNRTTLSDTOR *PFNRTTLSDTOR;
930 * Allocates a TLS entry (index).
932 * Example code:
933 * @code
934 RTTLS g_iTls = NIL_RTTLS;
938 // once for the process, allocate the TLS index
939 if (g_iTls == NIL_RTTLS)
940 g_iTls = RTTlsAlloc();
942 // set the thread-local value.
943 RTTlsSet(g_iTls, pMyData);
947 // get the thread-local value
948 PMYDATA pMyData = (PMYDATA)RTTlsGet(g_iTls);
950 @endcode
952 * @returns the index of the allocated TLS entry.
953 * @returns NIL_RTTLS on failure.
955 RTR3DECL(RTTLS) RTTlsAlloc(void);
958 * Variant of RTTlsAlloc that returns a status code.
960 * @returns IPRT status code.
961 * @retval VERR_NOT_SUPPORTED if pfnDestructor is non-NULL and the platform
962 * doesn't support this feature.
964 * @param piTls Where to store the index of the allocated TLS entry.
965 * This is set to NIL_RTTLS on failure.
966 * @param pfnDestructor Optional callback function for cleaning up on
967 * thread termination.
968 * @note In static builds on windows, the destructor will only be invoked for
969 * IPRT threads.
970 * @note There are probably OS specific restrictions on what operations you
971 * are allowed to perform from a TLS destructor, so keep it simple.
973 RTR3DECL(int) RTTlsAllocEx(PRTTLS piTls, PFNRTTLSDTOR pfnDestructor);
976 * Frees a TLS entry.
978 * @returns IPRT status code.
979 * @param iTls The index of the TLS entry.
981 RTR3DECL(int) RTTlsFree(RTTLS iTls);
984 * Get the (thread-local) value stored in a TLS entry.
986 * @returns value in given TLS entry.
987 * @retval NULL if RTTlsSet() has not yet been called on this thread, or if the
988 * TLS index is invalid.
990 * @param iTls The index of the TLS entry.
992 RTR3DECL(void *) RTTlsGet(RTTLS iTls);
995 * Get the value stored in a TLS entry.
997 * @returns IPRT status code.
998 * @param iTls The index of the TLS entry.
999 * @param ppvValue Where to store the value. The value will be NULL if
1000 * RTTlsSet has not yet been called on this thread.
1002 RTR3DECL(int) RTTlsGetEx(RTTLS iTls, void **ppvValue);
1005 * Set the value stored in an allocated TLS entry.
1007 * @returns IPRT status.
1008 * @param iTls The index of the TLS entry.
1009 * @param pvValue The value to store.
1011 * @remarks Note that NULL is considered a special value.
1013 RTR3DECL(int) RTTlsSet(RTTLS iTls, void *pvValue);
1015 /** @} */
1017 # endif /* IN_RING3 */
1018 #endif /* !IN_RC || defined(DOXYGEN_RUNNING) */
1020 /** @} */
1022 RT_C_DECLS_END
1024 #endif /* !IPRT_INCLUDED_thread_h */