VirtualBox

source: vbox/trunk/src/VBox/Runtime/common/misc/thread.cpp@ 25409

Last change on this file since 25409 was 25409, checked in by vboxsync, 15 years ago

IPRT,PDMCritSect,Main: Moved code dealing with lock counting from RTThread to RTLockValidator. Fixed thread termination assertion on windows.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 42.6 KB
Line 
1/* $Id: thread.cpp 25409 2009-12-15 15:04:41Z vboxsync $ */
2/** @file
3 * IPRT - Threads, common routines.
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 *
26 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
27 * Clara, CA 95054 USA or visit http://www.sun.com if you need
28 * additional information or have any questions.
29 */
30
31
32/*******************************************************************************
33* Header Files *
34*******************************************************************************/
35#define LOG_GROUP RTLOGGROUP_THREAD
36#include <iprt/thread.h>
37#include "internal/iprt.h"
38
39#include <iprt/log.h>
40#include <iprt/avl.h>
41#include <iprt/alloc.h>
42#include <iprt/assert.h>
43#include <iprt/lockvalidator.h>
44#include <iprt/semaphore.h>
45#ifdef IN_RING0
46# include <iprt/spinlock.h>
47#endif
48#include <iprt/asm.h>
49#include <iprt/err.h>
50#include <iprt/string.h>
51#include "internal/magics.h"
52#include "internal/thread.h"
53#include "internal/sched.h"
54#include "internal/process.h"
55
56
57/*******************************************************************************
58* Defined Constants And Macros *
59*******************************************************************************/
60#ifdef IN_RING0
61# define RT_THREAD_LOCK_TMP(Tmp) RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER
62# define RT_THREAD_LOCK_RW(Tmp) RTSpinlockAcquireNoInts(g_ThreadSpinlock, &(Tmp))
63# define RT_THREAD_UNLOCK_RW(Tmp) RTSpinlockReleaseNoInts(g_ThreadSpinlock, &(Tmp))
64# define RT_THREAD_LOCK_RD(Tmp) RTSpinlockAcquireNoInts(g_ThreadSpinlock, &(Tmp))
65# define RT_THREAD_UNLOCK_RD(Tmp) RTSpinlockReleaseNoInts(g_ThreadSpinlock, &(Tmp))
66#else
67# define RT_THREAD_LOCK_TMP(Tmp)
68# define RT_THREAD_LOCK_RW(Tmp) rtThreadLockRW()
69# define RT_THREAD_UNLOCK_RW(Tmp) rtThreadUnLockRW()
70# define RT_THREAD_LOCK_RD(Tmp) rtThreadLockRD()
71# define RT_THREAD_UNLOCK_RD(Tmp) rtThreadUnLockRD()
72#endif
73
74
75/*******************************************************************************
76* Global Variables *
77*******************************************************************************/
78/** The AVL thread containing the threads. */
79static PAVLPVNODECORE g_ThreadTree;
80#ifdef IN_RING3
81/** The RW lock protecting the tree. */
82static RTSEMRW g_ThreadRWSem = NIL_RTSEMRW;
83#else
84/** The spinlocks protecting the tree. */
85static RTSPINLOCK g_ThreadSpinlock = NIL_RTSPINLOCK;
86#endif
87
88
89/*******************************************************************************
90* Internal Functions *
91*******************************************************************************/
92static void rtThreadDestroy(PRTTHREADINT pThread);
93static int rtThreadAdopt(RTTHREADTYPE enmType, unsigned fFlags, uint32_t fIntFlags, const char *pszName);
94static void rtThreadRemoveLocked(PRTTHREADINT pThread);
95static PRTTHREADINT rtThreadAlloc(RTTHREADTYPE enmType, unsigned fFlags, uint32_t fIntFlags, const char *pszName);
96
97
98/** @page pg_rt_thread IPRT Thread Internals
99 *
100 * IPRT provides interface to whatever native threading that the host provides,
101 * preferably using a CRT level interface to better integrate with other libraries.
102 *
103 * Internally IPRT keeps track of threads by means of the RTTHREADINT structure.
104 * All the RTTHREADINT structures are kept in a AVL tree which is protected by a
105 * read/write lock for efficient access. A thread is inserted into the tree in
106 * three places in the code. The main thread is 'adopted' by IPRT on RTR3Init()
107 * by rtThreadAdopt(). When creating a new thread there the child and the parent
108 * race inserting the thread, this is rtThreadMain() and RTThreadCreate.
109 *
110 * RTTHREADINT objects are using reference counting as a mean of sticking around
111 * till no-one needs them any longer. Waitable threads is created with one extra
112 * reference so they won't go away until they are waited on. This introduces a
113 * major problem if we use the host thread identifier as key in the AVL tree - the
114 * host may reuse the thread identifier before the thread was waited on. So, on
115 * most platforms we are using the RTTHREADINT pointer as key and not the
116 * thread id. RTThreadSelf() then have to be implemented using a pointer stored
117 * in thread local storage (TLS).
118 *
119 * In Ring-0 we only try keep track of kernel threads created by RTThreadCreate
120 * at the moment. There we really only need the 'join' feature, but doing things
121 * the same way allow us to name threads and similar stuff.
122 */
123
124
125/**
126 * Initializes the thread database.
127 *
128 * @returns iprt status code.
129 */
130int rtThreadInit(void)
131{
132#ifdef IN_RING3
133 int rc = VINF_ALREADY_INITIALIZED;
134 if (g_ThreadRWSem == NIL_RTSEMRW)
135 {
136 /*
137 * We assume the caller is the 1st thread, which we'll call 'main'.
138 * But first, we'll create the semaphore.
139 */
140 rc = RTSemRWCreate(&g_ThreadRWSem);
141 if (RT_SUCCESS(rc))
142 {
143 rc = rtThreadNativeInit();
144 if (RT_SUCCESS(rc))
145 rc = rtThreadAdopt(RTTHREADTYPE_DEFAULT, 0, RTTHREADINT_FLAGS_MAIN, "main");
146 if (RT_SUCCESS(rc))
147 rc = rtSchedNativeCalcDefaultPriority(RTTHREADTYPE_DEFAULT);
148 if (RT_SUCCESS(rc))
149 return VINF_SUCCESS;
150
151 /* failed, clear out */
152 RTSemRWDestroy(g_ThreadRWSem);
153 g_ThreadRWSem = NIL_RTSEMRW;
154 }
155 }
156
157#elif defined(IN_RING0)
158
159 /*
160 * Create the spinlock and to native init.
161 */
162 Assert(g_ThreadSpinlock == NIL_RTSPINLOCK);
163 int rc = RTSpinlockCreate(&g_ThreadSpinlock);
164 if (RT_SUCCESS(rc))
165 {
166 rc = rtThreadNativeInit();
167 if (RT_SUCCESS(rc))
168 return VINF_SUCCESS;
169
170 /* failed, clear out */
171 RTSpinlockDestroy(g_ThreadSpinlock);
172 g_ThreadSpinlock = NIL_RTSPINLOCK;
173 }
174#else
175# error "!IN_RING0 && !IN_RING3"
176#endif
177 return rc;
178}
179
180
181/**
182 * Terminates the thread database.
183 */
184void rtThreadTerm(void)
185{
186#ifdef IN_RING3
187 /* we don't cleanup here yet */
188
189#elif defined(IN_RING0)
190 /* just destroy the spinlock and assume the thread is fine... */
191 RTSpinlockDestroy(g_ThreadSpinlock);
192 g_ThreadSpinlock = NIL_RTSPINLOCK;
193 if (g_ThreadTree != NULL)
194 AssertMsg2("WARNING: g_ThreadTree=%p\n", g_ThreadTree);
195#endif
196}
197
198
199/**
200 * Sets the thread state.
201 *
202 * @param pThread The thread.
203 * @param enmNewState The new thread state.
204 */
205DECLINLINE(void) rtThreadSetState(PRTTHREADINT pThread, RTTHREADSTATE enmNewState)
206{
207 AssertCompile(sizeof(pThread->enmState) == sizeof(uint32_t));
208 ASMAtomicWriteU32((uint32_t volatile *)&pThread->enmState, enmNewState);
209}
210
211#ifdef IN_RING3
212
213DECLINLINE(void) rtThreadLockRW(void)
214{
215 if (g_ThreadRWSem == NIL_RTSEMRW)
216 rtThreadInit();
217 int rc = RTSemRWRequestWrite(g_ThreadRWSem, RT_INDEFINITE_WAIT);
218 AssertReleaseRC(rc);
219}
220
221
222DECLINLINE(void) rtThreadLockRD(void)
223{
224 if (g_ThreadRWSem == NIL_RTSEMRW)
225 rtThreadInit();
226 int rc = RTSemRWRequestRead(g_ThreadRWSem, RT_INDEFINITE_WAIT);
227 AssertReleaseRC(rc);
228}
229
230
231DECLINLINE(void) rtThreadUnLockRW(void)
232{
233 int rc = RTSemRWReleaseWrite(g_ThreadRWSem);
234 AssertReleaseRC(rc);
235}
236
237
238DECLINLINE(void) rtThreadUnLockRD(void)
239{
240 int rc = RTSemRWReleaseRead(g_ThreadRWSem);
241 AssertReleaseRC(rc);
242}
243
244#endif /* IN_RING3 */
245
246
247/**
248 * Adopts the calling thread.
249 * No locks are taken or released by this function.
250 */
251static int rtThreadAdopt(RTTHREADTYPE enmType, unsigned fFlags, uint32_t fIntFlags, const char *pszName)
252{
253 Assert(!(fFlags & RTTHREADFLAGS_WAITABLE));
254 fFlags &= ~RTTHREADFLAGS_WAITABLE;
255
256 /*
257 * Allocate and insert the thread.
258 * (It is vital that rtThreadNativeAdopt updates the TLS before
259 * we try inserting the thread because of locking.)
260 */
261 int rc = VERR_NO_MEMORY;
262 PRTTHREADINT pThread = rtThreadAlloc(enmType, fFlags, RTTHREADINT_FLAGS_ALIEN | fIntFlags, pszName);
263 if (pThread)
264 {
265 RTNATIVETHREAD NativeThread = RTThreadNativeSelf();
266 rc = rtThreadNativeAdopt(pThread);
267 if (RT_SUCCESS(rc))
268 {
269 rtThreadInsert(pThread, NativeThread);
270 rtThreadSetState(pThread, RTTHREADSTATE_RUNNING);
271 rtThreadRelease(pThread);
272 }
273 }
274 return rc;
275}
276
277
278/**
279 * Adopts a non-IPRT thread.
280 *
281 * @returns IPRT status code.
282 * @param enmType The thread type.
283 * @param fFlags The thread flags. RTTHREADFLAGS_WAITABLE is not currently allowed.
284 * @param pszName The thread name. Optional.
285 * @param pThread Where to store the thread handle. Optional.
286 */
287RTDECL(int) RTThreadAdopt(RTTHREADTYPE enmType, unsigned fFlags, const char *pszName, PRTTHREAD pThread)
288{
289 AssertReturn(!(fFlags & RTTHREADFLAGS_WAITABLE), VERR_INVALID_PARAMETER);
290 AssertReturn(!pszName || VALID_PTR(pszName), VERR_INVALID_POINTER);
291 AssertReturn(!pThread || VALID_PTR(pThread), VERR_INVALID_POINTER);
292
293 int rc = VINF_SUCCESS;
294 RTTHREAD Thread = RTThreadSelf();
295 if (Thread == NIL_RTTHREAD)
296 {
297 /* generate a name if none was given. */
298 char szName[RTTHREAD_NAME_LEN];
299 if (!pszName || !*pszName)
300 {
301 static uint32_t s_i32AlienId = 0;
302 uint32_t i32Id = ASMAtomicIncU32(&s_i32AlienId);
303 RTStrPrintf(szName, sizeof(szName), "ALIEN-%RX32", i32Id);
304 pszName = szName;
305 }
306
307 /* try adopt it */
308 rc = rtThreadAdopt(enmType, fFlags, 0, pszName);
309 Thread = RTThreadSelf();
310 Log(("RTThreadAdopt: %RTthrd %RTnthrd '%s' enmType=%d fFlags=%#x rc=%Rrc\n",
311 Thread, RTThreadNativeSelf(), pszName, enmType, fFlags, rc));
312 }
313 else
314 Log(("RTThreadAdopt: %RTthrd %RTnthrd '%s' enmType=%d fFlags=%#x - already adopted!\n",
315 Thread, RTThreadNativeSelf(), pszName, enmType, fFlags));
316
317 if (pThread)
318 *pThread = Thread;
319 return rc;
320}
321RT_EXPORT_SYMBOL(RTThreadAdopt);
322
323
324/**
325 * Get the thread handle of the current thread, automatically adopting alien
326 * threads.
327 *
328 * @returns Thread handle.
329 */
330RTDECL(RTTHREAD) RTThreadSelfAutoAdopt(void)
331{
332 RTTHREAD hSelf = RTThreadSelf();
333 if (RT_UNLIKELY(hSelf == NIL_RTTHREAD))
334 RTThreadAdopt(RTTHREADTYPE_DEFAULT, 0, NULL, &hSelf);
335 return hSelf;
336}
337RT_EXPORT_SYMBOL(RTThreadSelfAutoAdopt);
338
339
340/**
341 * Allocates a per thread data structure and initializes the basic fields.
342 *
343 * @returns Pointer to per thread data structure.
344 * This is reference once.
345 * @returns NULL on failure.
346 * @param enmType The thread type.
347 * @param fFlags The thread flags.
348 * @param fIntFlags The internal thread flags.
349 * @param pszName Pointer to the thread name.
350 */
351PRTTHREADINT rtThreadAlloc(RTTHREADTYPE enmType, unsigned fFlags, uint32_t fIntFlags, const char *pszName)
352{
353 PRTTHREADINT pThread = (PRTTHREADINT)RTMemAllocZ(sizeof(RTTHREADINT));
354 if (pThread)
355 {
356 pThread->Core.Key = (void*)NIL_RTTHREAD;
357 pThread->u32Magic = RTTHREADINT_MAGIC;
358 size_t cchName = strlen(pszName);
359 if (cchName >= RTTHREAD_NAME_LEN)
360 cchName = RTTHREAD_NAME_LEN - 1;
361 memcpy(pThread->szName, pszName, cchName);
362 pThread->szName[cchName] = '\0';
363 pThread->cRefs = 2 + !!(fFlags & RTTHREADFLAGS_WAITABLE); /* And extra reference if waitable. */
364 pThread->rc = VERR_PROCESS_RUNNING; /** @todo get a better error code! */
365 pThread->enmType = enmType;
366 pThread->fFlags = fFlags;
367 pThread->fIntFlags = fIntFlags;
368 pThread->enmState = RTTHREADSTATE_INITIALIZING;
369 int rc = RTSemEventMultiCreate(&pThread->EventUser);
370 if (RT_SUCCESS(rc))
371 {
372 rc = RTSemEventMultiCreate(&pThread->EventTerminated);
373 if (RT_SUCCESS(rc))
374 return pThread;
375 RTSemEventMultiDestroy(pThread->EventUser);
376 }
377 RTMemFree(pThread);
378 }
379 return NULL;
380}
381
382
383/**
384 * Insert the per thread data structure into the tree.
385 *
386 * This can be called from both the thread it self and the parent,
387 * thus it must handle insertion failures in a nice manner.
388 *
389 * @param pThread Pointer to thread structure allocated by rtThreadAlloc().
390 * @param NativeThread The native thread id.
391 */
392void rtThreadInsert(PRTTHREADINT pThread, RTNATIVETHREAD NativeThread)
393{
394 Assert(pThread);
395 Assert(pThread->u32Magic == RTTHREADINT_MAGIC);
396
397 RT_THREAD_LOCK_TMP(Tmp);
398 RT_THREAD_LOCK_RW(Tmp);
399
400 /*
401 * Do not insert a terminated thread.
402 *
403 * This may happen if the thread finishes before the RTThreadCreate call
404 * gets this far. Since the OS may quickly reuse the native thread ID
405 * it should not be reinserted at this point.
406 */
407 if (rtThreadGetState(pThread) != RTTHREADSTATE_TERMINATED)
408 {
409 /*
410 * Before inserting we must check if there is a thread with this id
411 * in the tree already. We're racing parent and child on insert here
412 * so that the handle is valid in both ends when they return / start.
413 *
414 * If it's not ourself we find, it's a dead alien thread and we will
415 * unlink it from the tree. Alien threads will be released at this point.
416 */
417 PRTTHREADINT pThreadOther = (PRTTHREADINT)RTAvlPVGet(&g_ThreadTree, (void *)NativeThread);
418 if (pThreadOther != pThread)
419 {
420 /* remove dead alien if any */
421 if (pThreadOther)
422 {
423 AssertMsg(pThreadOther->fIntFlags & RTTHREADINT_FLAGS_ALIEN, ("%p:%s; %p:%s\n", pThread, pThread->szName, pThreadOther, pThreadOther->szName));
424 ASMAtomicBitClear(&pThread->fIntFlags, RTTHREADINT_FLAG_IN_TREE_BIT);
425 rtThreadRemoveLocked(pThreadOther);
426 if (pThreadOther->fIntFlags & RTTHREADINT_FLAGS_ALIEN)
427 rtThreadRelease(pThreadOther);
428 }
429
430 /* insert the thread */
431 ASMAtomicWritePtr(&pThread->Core.Key, (void *)NativeThread);
432 bool fRc = RTAvlPVInsert(&g_ThreadTree, &pThread->Core);
433 ASMAtomicOrU32(&pThread->fIntFlags, RTTHREADINT_FLAG_IN_TREE);
434
435 AssertReleaseMsg(fRc, ("Lock problem? %p (%RTnthrd) %s\n", pThread, NativeThread, pThread->szName));
436 NOREF(fRc);
437 }
438 }
439
440 RT_THREAD_UNLOCK_RW(Tmp);
441}
442
443
444/**
445 * Removes the thread from the AVL tree, call owns the tree lock
446 * and has cleared the RTTHREADINT_FLAG_IN_TREE bit.
447 *
448 * @param pThread The thread to remove.
449 */
450static void rtThreadRemoveLocked(PRTTHREADINT pThread)
451{
452 PRTTHREADINT pThread2 = (PRTTHREADINT)RTAvlPVRemove(&g_ThreadTree, pThread->Core.Key);
453#if !defined(RT_OS_OS2) /** @todo this asserts for threads created by NSPR */
454 AssertMsg(pThread2 == pThread, ("%p(%s) != %p (%p/%s)\n", pThread2, pThread2 ? pThread2->szName : "<null>",
455 pThread, pThread->Core.Key, pThread->szName));
456#endif
457 NOREF(pThread2);
458}
459
460
461/**
462 * Removes the thread from the AVL tree.
463 *
464 * @param pThread The thread to remove.
465 */
466static void rtThreadRemove(PRTTHREADINT pThread)
467{
468 RT_THREAD_LOCK_TMP(Tmp);
469 RT_THREAD_LOCK_RW(Tmp);
470 if (ASMAtomicBitTestAndClear(&pThread->fIntFlags, RTTHREADINT_FLAG_IN_TREE_BIT))
471 rtThreadRemoveLocked(pThread);
472 RT_THREAD_UNLOCK_RW(Tmp);
473}
474
475
476/**
477 * Checks if a thread is alive or not.
478 *
479 * @returns true if the thread is alive (or we don't really know).
480 * @returns false if the thread has surely terminate.
481 */
482DECLINLINE(bool) rtThreadIsAlive(PRTTHREADINT pThread)
483{
484 return !(pThread->fIntFlags & RTTHREADINT_FLAGS_TERMINATED);
485}
486
487
488/**
489 * Gets a thread by it's native ID.
490 *
491 * @returns pointer to the thread structure.
492 * @returns NULL if not a thread IPRT knows.
493 * @param NativeThread The native thread id.
494 */
495PRTTHREADINT rtThreadGetByNative(RTNATIVETHREAD NativeThread)
496{
497 /*
498 * Simple tree lookup.
499 */
500 RT_THREAD_LOCK_TMP(Tmp);
501 RT_THREAD_LOCK_RD(Tmp);
502 PRTTHREADINT pThread = (PRTTHREADINT)RTAvlPVGet(&g_ThreadTree, (void *)NativeThread);
503 RT_THREAD_UNLOCK_RD(Tmp);
504 return pThread;
505}
506
507
508/**
509 * Gets the per thread data structure for a thread handle.
510 *
511 * @returns Pointer to the per thread data structure for Thread.
512 * The caller must release the thread using rtThreadRelease().
513 * @returns NULL if Thread was not found.
514 * @param Thread Thread id which structure is to be returned.
515 */
516PRTTHREADINT rtThreadGet(RTTHREAD Thread)
517{
518 if ( Thread != NIL_RTTHREAD
519 && VALID_PTR(Thread))
520 {
521 PRTTHREADINT pThread = (PRTTHREADINT)Thread;
522 if ( pThread->u32Magic == RTTHREADINT_MAGIC
523 && pThread->cRefs > 0)
524 {
525 ASMAtomicIncU32(&pThread->cRefs);
526 return pThread;
527 }
528 }
529
530 AssertMsgFailed(("Thread=%RTthrd\n", Thread));
531 return NULL;
532}
533
534
535/**
536 * Release a per thread data structure.
537 *
538 * @returns New reference count.
539 * @param pThread The thread structure to release.
540 */
541uint32_t rtThreadRelease(PRTTHREADINT pThread)
542{
543 Assert(pThread);
544 uint32_t cRefs;
545 if (pThread->cRefs >= 1)
546 {
547 cRefs = ASMAtomicDecU32(&pThread->cRefs);
548 if (!cRefs)
549 rtThreadDestroy(pThread);
550 }
551 else
552 cRefs = 0;
553 return cRefs;
554}
555
556
557/**
558 * Destroys the per thread data.
559 *
560 * @param pThread The thread to destroy.
561 */
562static void rtThreadDestroy(PRTTHREADINT pThread)
563{
564 /*
565 * Remove it from the tree and mark it as dead.
566 *
567 * Threads that has seen rtThreadTerminate and should already have been
568 * removed from the tree. There is probably no thread that should
569 * require removing here. However, be careful making sure that cRefs
570 * isn't 0 if we do or we'll blow up because the strict locking code
571 * will be calling us back.
572 */
573 if (ASMBitTest(&pThread->fIntFlags, RTTHREADINT_FLAG_IN_TREE_BIT))
574 {
575 ASMAtomicIncU32(&pThread->cRefs);
576 rtThreadRemove(pThread);
577 ASMAtomicDecU32(&pThread->cRefs);
578 }
579 ASMAtomicXchgU32(&pThread->u32Magic, RTTHREADINT_MAGIC_DEAD);
580
581 /*
582 * Free resources.
583 */
584 ASMAtomicWritePtr(&pThread->Core.Key, (void *)NIL_RTTHREAD);
585 pThread->enmType = RTTHREADTYPE_INVALID;
586 RTSemEventMultiDestroy(pThread->EventUser);
587 pThread->EventUser = NIL_RTSEMEVENTMULTI;
588 if (pThread->EventTerminated != NIL_RTSEMEVENTMULTI)
589 {
590 RTSemEventMultiDestroy(pThread->EventTerminated);
591 pThread->EventTerminated = NIL_RTSEMEVENTMULTI;
592 }
593 RTMemFree(pThread);
594}
595
596
597/**
598 * Terminates the thread.
599 * Called by the thread wrapper function when the thread terminates.
600 *
601 * @param pThread The thread structure.
602 * @param rc The thread result code.
603 */
604void rtThreadTerminate(PRTTHREADINT pThread, int rc)
605{
606 Assert(pThread->cRefs >= 1);
607
608#ifdef IPRT_WITH_GENERIC_TLS
609 /*
610 * Destroy TLS entries.
611 */
612 rtThreadTlsDestruction(pThread);
613#endif /* IPRT_WITH_GENERIC_TLS */
614
615 /*
616 * Set the rc, mark it terminated and signal anyone waiting.
617 */
618 pThread->rc = rc;
619 rtThreadSetState(pThread, RTTHREADSTATE_TERMINATED);
620 ASMAtomicOrU32(&pThread->fIntFlags, RTTHREADINT_FLAGS_TERMINATED);
621 if (pThread->EventTerminated != NIL_RTSEMEVENTMULTI)
622 RTSemEventMultiSignal(pThread->EventTerminated);
623
624 /*
625 * Remove the thread from the tree so that there will be no
626 * key clashes in the AVL tree and release our reference to ourself.
627 */
628 rtThreadRemove(pThread);
629 rtThreadRelease(pThread);
630}
631
632
633/**
634 * The common thread main function.
635 * This is called by rtThreadNativeMain().
636 *
637 * @returns The status code of the thread.
638 * pThread is dereference by the thread before returning!
639 * @param pThread The thread structure.
640 * @param NativeThread The native thread id.
641 * @param pszThreadName The name of the thread (purely a dummy for backtrace).
642 */
643int rtThreadMain(PRTTHREADINT pThread, RTNATIVETHREAD NativeThread, const char *pszThreadName)
644{
645 NOREF(pszThreadName);
646 rtThreadInsert(pThread, NativeThread);
647 Log(("rtThreadMain: Starting: pThread=%p NativeThread=%RTnthrd Name=%s pfnThread=%p pvUser=%p\n",
648 pThread, NativeThread, pThread->szName, pThread->pfnThread, pThread->pvUser));
649
650 /*
651 * Change the priority.
652 */
653 int rc = rtThreadNativeSetPriority(pThread, pThread->enmType);
654#ifdef IN_RING3
655 AssertMsgRC(rc, ("Failed to set priority of thread %p (%RTnthrd / %s) to enmType=%d enmPriority=%d rc=%Rrc\n",
656 pThread, NativeThread, pThread->szName, pThread->enmType, g_enmProcessPriority, rc));
657#else
658 AssertMsgRC(rc, ("Failed to set priority of thread %p (%RTnthrd / %s) to enmType=%d rc=%Rrc\n",
659 pThread, NativeThread, pThread->szName, pThread->enmType, rc));
660#endif
661
662 /*
663 * Call thread function and terminate when it returns.
664 */
665 rtThreadSetState(pThread, RTTHREADSTATE_RUNNING);
666 rc = pThread->pfnThread(pThread, pThread->pvUser);
667
668 /*
669 * Paranoia checks for leftover resources.
670 */
671#ifdef RTSEMRW_STRICT
672 int32_t cWrite = ASMAtomicReadS32(&pThread->cWriteLocks);
673 Assert(!cWrite);
674 int32_t cRead = ASMAtomicReadS32(&pThread->cReadLocks);
675 Assert(!cRead);
676#endif
677
678 Log(("rtThreadMain: Terminating: rc=%d pThread=%p NativeThread=%RTnthrd Name=%s pfnThread=%p pvUser=%p\n",
679 rc, pThread, NativeThread, pThread->szName, pThread->pfnThread, pThread->pvUser));
680 rtThreadTerminate(pThread, rc);
681 return rc;
682}
683
684
685/**
686 * Create a new thread.
687 *
688 * @returns iprt status code.
689 * @param pThread Where to store the thread handle to the new thread. (optional)
690 * @param pfnThread The thread function.
691 * @param pvUser User argument.
692 * @param cbStack The size of the stack for the new thread.
693 * Use 0 for the default stack size.
694 * @param enmType The thread type. Used for deciding scheduling attributes
695 * of the thread.
696 * @param fFlags Flags of the RTTHREADFLAGS type (ORed together).
697 * @param pszName Thread name.
698 */
699RTDECL(int) RTThreadCreate(PRTTHREAD pThread, PFNRTTHREAD pfnThread, void *pvUser, size_t cbStack,
700 RTTHREADTYPE enmType, unsigned fFlags, const char *pszName)
701{
702 LogFlow(("RTThreadCreate: pThread=%p pfnThread=%p pvUser=%p cbStack=%#x enmType=%d fFlags=%#x pszName=%p:{%s}\n",
703 pThread, pfnThread, pvUser, cbStack, enmType, fFlags, pszName, pszName));
704
705 /*
706 * Validate input.
707 */
708 if (!VALID_PTR(pThread) && pThread)
709 {
710 Assert(VALID_PTR(pThread));
711 return VERR_INVALID_PARAMETER;
712 }
713 if (!VALID_PTR(pfnThread))
714 {
715 Assert(VALID_PTR(pfnThread));
716 return VERR_INVALID_PARAMETER;
717 }
718 if (!pszName || !*pszName || strlen(pszName) >= RTTHREAD_NAME_LEN)
719 {
720 AssertMsgFailed(("pszName=%s (max len is %d because of logging)\n", pszName, RTTHREAD_NAME_LEN - 1));
721 return VERR_INVALID_PARAMETER;
722 }
723 if (fFlags & ~RTTHREADFLAGS_MASK)
724 {
725 AssertMsgFailed(("fFlags=%#x\n", fFlags));
726 return VERR_INVALID_PARAMETER;
727 }
728
729 /*
730 * Allocate thread argument.
731 */
732 int rc;
733 PRTTHREADINT pThreadInt = rtThreadAlloc(enmType, fFlags, 0, pszName);
734 if (pThreadInt)
735 {
736 pThreadInt->pfnThread = pfnThread;
737 pThreadInt->pvUser = pvUser;
738 pThreadInt->cbStack = cbStack;
739
740 RTNATIVETHREAD NativeThread;
741 rc = rtThreadNativeCreate(pThreadInt, &NativeThread);
742 if (RT_SUCCESS(rc))
743 {
744 rtThreadInsert(pThreadInt, NativeThread);
745 rtThreadRelease(pThreadInt);
746 Log(("RTThreadCreate: Created thread %p (%p) %s\n", pThreadInt, NativeThread, pszName));
747 if (pThread)
748 *pThread = pThreadInt;
749 return VINF_SUCCESS;
750 }
751
752 pThreadInt->cRefs = 1;
753 rtThreadRelease(pThreadInt);
754 }
755 else
756 rc = VERR_NO_TMP_MEMORY;
757 LogFlow(("RTThreadCreate: Failed to create thread, rc=%Rrc\n", rc));
758 AssertReleaseRC(rc);
759 return rc;
760}
761RT_EXPORT_SYMBOL(RTThreadCreate);
762
763
764/**
765 * Create a new thread.
766 *
767 * Same as RTThreadCreate except the name is given in the RTStrPrintfV form.
768 *
769 * @returns iprt status code.
770 * @param pThread See RTThreadCreate.
771 * @param pfnThread See RTThreadCreate.
772 * @param pvUser See RTThreadCreate.
773 * @param cbStack See RTThreadCreate.
774 * @param enmType See RTThreadCreate.
775 * @param fFlags See RTThreadCreate.
776 * @param pszName Thread name format.
777 * @param va Format arguments.
778 */
779RTDECL(int) RTThreadCreateV(PRTTHREAD pThread, PFNRTTHREAD pfnThread, void *pvUser, size_t cbStack,
780 RTTHREADTYPE enmType, uint32_t fFlags, const char *pszNameFmt, va_list va)
781{
782 char szName[RTTHREAD_NAME_LEN * 2];
783 RTStrPrintfV(szName, sizeof(szName), pszNameFmt, va);
784 return RTThreadCreate(pThread, pfnThread, pvUser, cbStack, enmType, fFlags, szName);
785}
786RT_EXPORT_SYMBOL(RTThreadCreateV);
787
788
789/**
790 * Create a new thread.
791 *
792 * Same as RTThreadCreate except the name is given in the RTStrPrintf form.
793 *
794 * @returns iprt status code.
795 * @param pThread See RTThreadCreate.
796 * @param pfnThread See RTThreadCreate.
797 * @param pvUser See RTThreadCreate.
798 * @param cbStack See RTThreadCreate.
799 * @param enmType See RTThreadCreate.
800 * @param fFlags See RTThreadCreate.
801 * @param pszName Thread name format.
802 * @param ... Format arguments.
803 */
804RTDECL(int) RTThreadCreateF(PRTTHREAD pThread, PFNRTTHREAD pfnThread, void *pvUser, size_t cbStack,
805 RTTHREADTYPE enmType, uint32_t fFlags, const char *pszNameFmt, ...)
806{
807 va_list va;
808 va_start(va, pszNameFmt);
809 int rc = RTThreadCreateV(pThread, pfnThread, pvUser, cbStack, enmType, fFlags, pszNameFmt, va);
810 va_end(va);
811 return rc;
812}
813RT_EXPORT_SYMBOL(RTThreadCreateF);
814
815
816/**
817 * Gets the native thread id of a IPRT thread.
818 *
819 * @returns The native thread id.
820 * @param Thread The IPRT thread.
821 */
822RTDECL(RTNATIVETHREAD) RTThreadGetNative(RTTHREAD Thread)
823{
824 PRTTHREADINT pThread = rtThreadGet(Thread);
825 if (pThread)
826 {
827 RTNATIVETHREAD NativeThread = (RTNATIVETHREAD)pThread->Core.Key;
828 rtThreadRelease(pThread);
829 return NativeThread;
830 }
831 return NIL_RTNATIVETHREAD;
832}
833RT_EXPORT_SYMBOL(RTThreadGetNative);
834
835
836/**
837 * Gets the IPRT thread of a native thread.
838 *
839 * @returns The IPRT thread handle
840 * @returns NIL_RTTHREAD if not a thread known to IPRT.
841 * @param NativeThread The native thread handle/id.
842 */
843RTDECL(RTTHREAD) RTThreadFromNative(RTNATIVETHREAD NativeThread)
844{
845 PRTTHREADINT pThread = rtThreadGetByNative(NativeThread);
846 if (pThread)
847 return pThread;
848 return NIL_RTTHREAD;
849}
850RT_EXPORT_SYMBOL(RTThreadFromNative);
851
852
853/**
854 * Gets the name of the current thread thread.
855 *
856 * @returns Pointer to readonly name string.
857 * @returns NULL on failure.
858 */
859RTDECL(const char *) RTThreadSelfName(void)
860{
861 RTTHREAD Thread = RTThreadSelf();
862 if (Thread != NIL_RTTHREAD)
863 {
864 PRTTHREADINT pThread = rtThreadGet(Thread);
865 if (pThread)
866 {
867 const char *szName = pThread->szName;
868 rtThreadRelease(pThread);
869 return szName;
870 }
871 }
872 return NULL;
873}
874RT_EXPORT_SYMBOL(RTThreadSelfName);
875
876
877/**
878 * Gets the name of a thread.
879 *
880 * @returns Pointer to readonly name string.
881 * @returns NULL on failure.
882 * @param Thread Thread handle of the thread to query the name of.
883 */
884RTDECL(const char *) RTThreadGetName(RTTHREAD Thread)
885{
886 if (Thread == NIL_RTTHREAD)
887 return NULL;
888 PRTTHREADINT pThread = rtThreadGet(Thread);
889 if (pThread)
890 {
891 const char *szName = pThread->szName;
892 rtThreadRelease(pThread);
893 return szName;
894 }
895 return NULL;
896}
897RT_EXPORT_SYMBOL(RTThreadGetName);
898
899
900/**
901 * Sets the name of a thread.
902 *
903 * @returns iprt status code.
904 * @param Thread Thread handle of the thread to query the name of.
905 * @param pszName The thread name.
906 */
907RTDECL(int) RTThreadSetName(RTTHREAD Thread, const char *pszName)
908{
909 /*
910 * Validate input.
911 */
912 size_t cchName = strlen(pszName);
913 if (cchName >= RTTHREAD_NAME_LEN)
914 {
915 AssertMsgFailed(("pszName=%s is too long, max is %d\n", pszName, RTTHREAD_NAME_LEN - 1));
916 return VERR_INVALID_PARAMETER;
917 }
918 PRTTHREADINT pThread = rtThreadGet(Thread);
919 if (!pThread)
920 return VERR_INVALID_HANDLE;
921
922 /*
923 * Update the name.
924 */
925 pThread->szName[cchName] = '\0'; /* paranoia */
926 memcpy(pThread->szName, pszName, cchName);
927 rtThreadRelease(pThread);
928 return VINF_SUCCESS;
929}
930RT_EXPORT_SYMBOL(RTThreadSetName);
931
932
933/**
934 * Checks if the specified thread is the main thread.
935 *
936 * @returns true if it is, false if it isn't.
937 *
938 * @param hThread The thread handle.
939 *
940 * @remarks This function may not return the correct value when RTR3Init was
941 * called on a thread of the than the main one. This could for
942 * instance happen when the DLL/DYLIB/SO containing IPRT is dynamically
943 * loaded at run time by a different thread.
944 */
945RTDECL(bool) RTThreadIsMain(RTTHREAD hThread)
946{
947 PRTTHREADINT pThread = rtThreadGet(hThread);
948 if (pThread)
949 {
950 bool fRc = !!(pThread->fIntFlags & RTTHREADINT_FLAGS_MAIN);
951 rtThreadRelease(pThread);
952 return fRc;
953 }
954 return false;
955}
956RT_EXPORT_SYMBOL(RTThreadIsMain);
957
958
959/**
960 * Signal the user event.
961 *
962 * @returns iprt status code.
963 */
964RTDECL(int) RTThreadUserSignal(RTTHREAD Thread)
965{
966 int rc;
967 PRTTHREADINT pThread = rtThreadGet(Thread);
968 if (pThread)
969 {
970 rc = RTSemEventMultiSignal(pThread->EventUser);
971 rtThreadRelease(pThread);
972 }
973 else
974 rc = VERR_INVALID_HANDLE;
975 return rc;
976}
977RT_EXPORT_SYMBOL(RTThreadUserSignal);
978
979
980/**
981 * Wait for the user event, resume on interruption.
982 *
983 * @returns iprt status code.
984 * @param Thread The thread to wait for.
985 * @param cMillies The number of milliseconds to wait. Use RT_INDEFINITE_WAIT for
986 * an indefinite wait.
987 */
988RTDECL(int) RTThreadUserWait(RTTHREAD Thread, unsigned cMillies)
989{
990 int rc;
991 PRTTHREADINT pThread = rtThreadGet(Thread);
992 if (pThread)
993 {
994 rc = RTSemEventMultiWait(pThread->EventUser, cMillies);
995 rtThreadRelease(pThread);
996 }
997 else
998 rc = VERR_INVALID_HANDLE;
999 return rc;
1000}
1001RT_EXPORT_SYMBOL(RTThreadUserWait);
1002
1003
1004/**
1005 * Wait for the user event, return on interruption.
1006 *
1007 * @returns iprt status code.
1008 * @param Thread The thread to wait for.
1009 * @param cMillies The number of milliseconds to wait. Use RT_INDEFINITE_WAIT for
1010 * an indefinite wait.
1011 */
1012RTDECL(int) RTThreadUserWaitNoResume(RTTHREAD Thread, unsigned cMillies)
1013{
1014 int rc;
1015 PRTTHREADINT pThread = rtThreadGet(Thread);
1016 if (pThread)
1017 {
1018 rc = RTSemEventMultiWaitNoResume(pThread->EventUser, cMillies);
1019 rtThreadRelease(pThread);
1020 }
1021 else
1022 rc = VERR_INVALID_HANDLE;
1023 return rc;
1024}
1025RT_EXPORT_SYMBOL(RTThreadUserWaitNoResume);
1026
1027
1028/**
1029 * Reset the user event.
1030 *
1031 * @returns iprt status code.
1032 * @param Thread The thread to reset.
1033 */
1034RTDECL(int) RTThreadUserReset(RTTHREAD Thread)
1035{
1036 int rc;
1037 PRTTHREADINT pThread = rtThreadGet(Thread);
1038 if (pThread)
1039 {
1040 rc = RTSemEventMultiReset(pThread->EventUser);
1041 rtThreadRelease(pThread);
1042 }
1043 else
1044 rc = VERR_INVALID_HANDLE;
1045 return rc;
1046}
1047RT_EXPORT_SYMBOL(RTThreadUserReset);
1048
1049
1050/**
1051 * Wait for the thread to terminate.
1052 *
1053 * @returns iprt status code.
1054 * @param Thread The thread to wait for.
1055 * @param cMillies The number of milliseconds to wait. Use RT_INDEFINITE_WAIT for
1056 * an indefinite wait.
1057 * @param prc Where to store the return code of the thread. Optional.
1058 * @param fAutoResume Whether or not to resume the wait on VERR_INTERRUPTED.
1059 */
1060static int rtThreadWait(RTTHREAD Thread, unsigned cMillies, int *prc, bool fAutoResume)
1061{
1062 int rc = VERR_INVALID_HANDLE;
1063 if (Thread != NIL_RTTHREAD)
1064 {
1065 PRTTHREADINT pThread = rtThreadGet(Thread);
1066 if (pThread)
1067 {
1068 if (pThread->fFlags & RTTHREADFLAGS_WAITABLE)
1069 {
1070 if (fAutoResume)
1071 rc = RTSemEventMultiWait(pThread->EventTerminated, cMillies);
1072 else
1073 rc = RTSemEventMultiWaitNoResume(pThread->EventTerminated, cMillies);
1074 if (RT_SUCCESS(rc))
1075 {
1076 if (prc)
1077 *prc = pThread->rc;
1078
1079 /*
1080 * If the thread is marked as waitable, we'll do one additional
1081 * release in order to free up the thread structure (see how we
1082 * init cRef in rtThreadAlloc()).
1083 */
1084 if (ASMAtomicBitTestAndClear(&pThread->fFlags, RTTHREADFLAGS_WAITABLE_BIT))
1085 rtThreadRelease(pThread);
1086 }
1087 }
1088 else
1089 {
1090 rc = VERR_THREAD_NOT_WAITABLE;
1091 AssertRC(rc);
1092 }
1093 rtThreadRelease(pThread);
1094 }
1095 }
1096 return rc;
1097}
1098
1099
1100/**
1101 * Wait for the thread to terminate, resume on interruption.
1102 *
1103 * @returns iprt status code.
1104 * Will not return VERR_INTERRUPTED.
1105 * @param Thread The thread to wait for.
1106 * @param cMillies The number of milliseconds to wait. Use RT_INDEFINITE_WAIT for
1107 * an indefinite wait.
1108 * @param prc Where to store the return code of the thread. Optional.
1109 */
1110RTDECL(int) RTThreadWait(RTTHREAD Thread, unsigned cMillies, int *prc)
1111{
1112 int rc = rtThreadWait(Thread, cMillies, prc, true);
1113 Assert(rc != VERR_INTERRUPTED);
1114 return rc;
1115}
1116RT_EXPORT_SYMBOL(RTThreadWait);
1117
1118
1119/**
1120 * Wait for the thread to terminate, return on interruption.
1121 *
1122 * @returns iprt status code.
1123 * @param Thread The thread to wait for.
1124 * @param cMillies The number of milliseconds to wait. Use RT_INDEFINITE_WAIT for
1125 * an indefinite wait.
1126 * @param prc Where to store the return code of the thread. Optional.
1127 */
1128RTDECL(int) RTThreadWaitNoResume(RTTHREAD Thread, unsigned cMillies, int *prc)
1129{
1130 return rtThreadWait(Thread, cMillies, prc, false);
1131}
1132RT_EXPORT_SYMBOL(RTThreadWaitNoResume);
1133
1134
1135/**
1136 * Changes the type of the specified thread.
1137 *
1138 * @returns iprt status code.
1139 * @param Thread The thread which type should be changed.
1140 * @param enmType The new thread type.
1141 */
1142RTDECL(int) RTThreadSetType(RTTHREAD Thread, RTTHREADTYPE enmType)
1143{
1144 /*
1145 * Validate input.
1146 */
1147 int rc;
1148 if ( enmType > RTTHREADTYPE_INVALID
1149 && enmType < RTTHREADTYPE_END)
1150 {
1151 PRTTHREADINT pThread = rtThreadGet(Thread);
1152 if (pThread)
1153 {
1154 if (rtThreadIsAlive(pThread))
1155 {
1156 /*
1157 * Do the job.
1158 */
1159 RT_THREAD_LOCK_TMP(Tmp);
1160 RT_THREAD_LOCK_RW(Tmp);
1161 rc = rtThreadNativeSetPriority(pThread, enmType);
1162 if (RT_SUCCESS(rc))
1163 ASMAtomicXchgSize(&pThread->enmType, enmType);
1164 RT_THREAD_UNLOCK_RW(Tmp);
1165 if (RT_FAILURE(rc))
1166 Log(("RTThreadSetType: failed on thread %p (%s), rc=%Rrc!!!\n", Thread, pThread->szName, rc));
1167 }
1168 else
1169 rc = VERR_THREAD_IS_DEAD;
1170 rtThreadRelease(pThread);
1171 }
1172 else
1173 rc = VERR_INVALID_HANDLE;
1174 }
1175 else
1176 {
1177 AssertMsgFailed(("enmType=%d\n", enmType));
1178 rc = VERR_INVALID_PARAMETER;
1179 }
1180 return rc;
1181}
1182RT_EXPORT_SYMBOL(RTThreadSetType);
1183
1184
1185/**
1186 * Gets the type of the specified thread.
1187 *
1188 * @returns The thread type.
1189 * @returns RTTHREADTYPE_INVALID if the thread handle is invalid.
1190 * @param Thread The thread in question.
1191 */
1192RTDECL(RTTHREADTYPE) RTThreadGetType(RTTHREAD Thread)
1193{
1194 RTTHREADTYPE enmType = RTTHREADTYPE_INVALID;
1195 PRTTHREADINT pThread = rtThreadGet(Thread);
1196 if (pThread)
1197 {
1198 enmType = pThread->enmType;
1199 rtThreadRelease(pThread);
1200 }
1201 return enmType;
1202}
1203RT_EXPORT_SYMBOL(RTThreadGetType);
1204
1205#ifdef IN_RING3
1206
1207/**
1208 * Recalculates scheduling attributes for the default process
1209 * priority using the specified priority type for the calling thread.
1210 *
1211 * The scheduling attributes are targeted at threads and they are protected
1212 * by the thread read-write semaphore, that's why RTProc is forwarding the
1213 * operation to RTThread.
1214 *
1215 * @returns iprt status code.
1216 * @remarks Will only work for strict builds.
1217 */
1218int rtThreadDoCalcDefaultPriority(RTTHREADTYPE enmType)
1219{
1220 RT_THREAD_LOCK_TMP(Tmp);
1221 RT_THREAD_LOCK_RW(Tmp);
1222 int rc = rtSchedNativeCalcDefaultPriority(enmType);
1223 RT_THREAD_UNLOCK_RW(Tmp);
1224 return rc;
1225}
1226
1227
1228/**
1229 * Thread enumerator - sets the priority of one thread.
1230 *
1231 * @returns 0 to continue.
1232 * @returns !0 to stop. In our case a VERR_ code.
1233 * @param pNode The thread node.
1234 * @param pvUser The new priority.
1235 */
1236static DECLCALLBACK(int) rtThreadSetPriorityOne(PAVLPVNODECORE pNode, void *pvUser)
1237{
1238 PRTTHREADINT pThread = (PRTTHREADINT)pNode;
1239 if (!rtThreadIsAlive(pThread))
1240 return VINF_SUCCESS;
1241 int rc = rtThreadNativeSetPriority(pThread, pThread->enmType);
1242 if (RT_SUCCESS(rc)) /* hide any warnings */
1243 return VINF_SUCCESS;
1244 return rc;
1245}
1246
1247
1248/**
1249 * Attempts to alter the priority of the current process.
1250 *
1251 * The scheduling attributes are targeted at threads and they are protected
1252 * by the thread read-write semaphore, that's why RTProc is forwarding the
1253 * operation to RTThread. This operation also involves updating all thread
1254 * which is much faster done from RTThread.
1255 *
1256 * @returns iprt status code.
1257 * @param enmPriority The new priority.
1258 */
1259int rtThreadDoSetProcPriority(RTPROCPRIORITY enmPriority)
1260{
1261 LogFlow(("rtThreadDoSetProcPriority: enmPriority=%d\n", enmPriority));
1262
1263 /*
1264 * First validate that we're allowed by the OS to use all the
1265 * scheduling attributes defined by the specified process priority.
1266 */
1267 RT_THREAD_LOCK_TMP(Tmp);
1268 RT_THREAD_LOCK_RW(Tmp);
1269 int rc = rtProcNativeSetPriority(enmPriority);
1270 if (RT_SUCCESS(rc))
1271 {
1272 /*
1273 * Update the priority of existing thread.
1274 */
1275 rc = RTAvlPVDoWithAll(&g_ThreadTree, true, rtThreadSetPriorityOne, NULL);
1276 if (RT_SUCCESS(rc))
1277 ASMAtomicXchgSize(&g_enmProcessPriority, enmPriority);
1278 else
1279 {
1280 /*
1281 * Failed, restore the priority.
1282 */
1283 rtProcNativeSetPriority(g_enmProcessPriority);
1284 RTAvlPVDoWithAll(&g_ThreadTree, true, rtThreadSetPriorityOne, NULL);
1285 }
1286 }
1287 RT_THREAD_UNLOCK_RW(Tmp);
1288 LogFlow(("rtThreadDoSetProcPriority: returns %Rrc\n", rc));
1289 return rc;
1290}
1291
1292
1293/**
1294 * Change the thread state to blocking.
1295 *
1296 * @param hThread The current thread.
1297 * @param enmState The sleep state.
1298 */
1299RTDECL(void) RTThreadBlocking(RTTHREAD hThread, RTTHREADSTATE enmState)
1300{
1301 Assert(RTTHREAD_IS_SLEEPING(enmState));
1302 PRTTHREADINT pThread = hThread;
1303 if (hThread && rtThreadGetState(pThread) != RTTHREADSTATE_RUNNING)
1304 rtThreadSetState(pThread, enmState);
1305}
1306RT_EXPORT_SYMBOL(RTThreadBlocking);
1307
1308
1309/**
1310 * Unblocks a thread.
1311 *
1312 * This function is paired with rtThreadBlocking.
1313 *
1314 * @param hThread The current thread.
1315 * @param enmCurState The current state, used to check for nested blocking.
1316 * The new state will be running.
1317 */
1318RTDECL(void) RTThreadUnblocked(RTTHREAD hThread, RTTHREADSTATE enmCurState)
1319{
1320 if (hThread && rtThreadGetState(hThread) == enmCurState)
1321 rtThreadSetState(hThread, RTTHREADSTATE_RUNNING);
1322}
1323RT_EXPORT_SYMBOL(RTThreadUnblocked);
1324
1325
1326/**
1327 * Translate a thread state into a string.
1328 *
1329 * @returns Pointer to a read-only string containing the state name.
1330 * @param enmState The state.
1331 */
1332RTDECL(const char *) RTThreadStateName(RTTHREADSTATE enmState)
1333{
1334 switch (enmState)
1335 {
1336 case RTTHREADSTATE_INVALID: return "INVALID";
1337 case RTTHREADSTATE_INITIALIZING: return "INITIALIZING";
1338 case RTTHREADSTATE_TERMINATED: return "TERMINATED";
1339 case RTTHREADSTATE_RUNNING: return "RUNNING";
1340 case RTTHREADSTATE_CRITSECT: return "CRITSECT";
1341 case RTTHREADSTATE_EVENT: return "EVENT";
1342 case RTTHREADSTATE_EVENT_MULTI: return "EVENT_MULTI";
1343 case RTTHREADSTATE_FAST_MUTEX: return "FAST_MUTEX";
1344 case RTTHREADSTATE_MUTEX: return "MUTEX";
1345 case RTTHREADSTATE_RW_READ: return "RW_READ";
1346 case RTTHREADSTATE_RW_WRITE: return "RW_WRITE";
1347 case RTTHREADSTATE_SLEEP: return "SLEEP";
1348 case RTTHREADSTATE_SPIN_MUTEX: return "SPIN_MUTEX";
1349 default: return "UnknownThreadState";
1350 }
1351}
1352RT_EXPORT_SYMBOL(RTThreadStateName);
1353
1354#endif /* IN_RING3 */
1355#ifdef IPRT_WITH_GENERIC_TLS
1356
1357/**
1358 * Thread enumerator - clears a TLS entry.
1359 *
1360 * @returns 0.
1361 * @param pNode The thread node.
1362 * @param pvUser The TLS index.
1363 */
1364static DECLCALLBACK(int) rtThreadClearTlsEntryCallback(PAVLPVNODECORE pNode, void *pvUser)
1365{
1366 PRTTHREADINT pThread = (PRTTHREADINT)pNode;
1367 RTTLS iTls = (RTTLS)(uintptr_t)pvUser;
1368 ASMAtomicWritePtr(&pThread->apvTlsEntries[iTls], NULL);
1369 return 0;
1370}
1371
1372
1373/**
1374 * Helper for the generic TLS implementation that clears a given TLS
1375 * entry on all threads.
1376 *
1377 * @param iTls The TLS entry. (valid)
1378 */
1379void rtThreadClearTlsEntry(RTTLS iTls)
1380{
1381 RT_THREAD_LOCK_TMP(Tmp);
1382 RT_THREAD_LOCK_RD(Tmp);
1383 RTAvlPVDoWithAll(&g_ThreadTree, true /* fFromLeft*/, rtThreadClearTlsEntryCallback, (void *)(uintptr_t)iTls);
1384 RT_THREAD_UNLOCK_RD(Tmp);
1385}
1386
1387#endif /* IPRT_WITH_GENERIC_TLS */
1388
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette