thread.cpp revision 88acfa6629a7976c0583c1712d2b5b22a87a5121
/* $Id$ */
/** @file
* IPRT - Threads, common routines.
*/
/*
* Copyright (C) 2006-2007 Sun Microsystems, Inc.
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 USA or visit http://www.sun.com if you need
* additional information or have any questions.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#define LOG_GROUP RTLOGGROUP_THREAD
#include <iprt/lockvalidator.h>
#include <iprt/semaphore.h>
#ifdef IN_RING0
# include <iprt/spinlock.h>
#endif
/*******************************************************************************
* Defined Constants And Macros *
*******************************************************************************/
#ifdef IN_RING0
#else
# define RT_THREAD_LOCK_TMP(Tmp)
#endif
/*******************************************************************************
* Global Variables *
*******************************************************************************/
/** The AVL thread containing the threads. */
static PAVLPVNODECORE g_ThreadTree;
#ifdef IN_RING3
/** The RW lock protecting the tree. */
#else
/** The spinlocks protecting the tree. */
#endif
/*******************************************************************************
* Internal Functions *
*******************************************************************************/
static int rtThreadAdopt(RTTHREADTYPE enmType, unsigned fFlags, uint32_t fIntFlags, const char *pszName);
static PRTTHREADINT rtThreadAlloc(RTTHREADTYPE enmType, unsigned fFlags, uint32_t fIntFlags, const char *pszName);
/** @page pg_rt_thread IPRT Thread Internals
*
* IPRT provides interface to whatever native threading that the host provides,
* preferably using a CRT level interface to better integrate with other libraries.
*
* Internally IPRT keeps track of threads by means of the RTTHREADINT structure.
* All the RTTHREADINT structures are kept in a AVL tree which is protected by a
* three places in the code. The main thread is 'adopted' by IPRT on RTR3Init()
* by rtThreadAdopt(). When creating a new thread there the child and the parent
* race inserting the thread, this is rtThreadMain() and RTThreadCreate.
*
* RTTHREADINT objects are using reference counting as a mean of sticking around
* till no-one needs them any longer. Waitable threads is created with one extra
* reference so they won't go away until they are waited on. This introduces a
* major problem if we use the host thread identifier as key in the AVL tree - the
* host may reuse the thread identifier before the thread was waited on. So, on
* most platforms we are using the RTTHREADINT pointer as key and not the
* thread id. RTThreadSelf() then have to be implemented using a pointer stored
* in thread local storage (TLS).
*
* In Ring-0 we only try keep track of kernel threads created by RTThreadCreate
* at the moment. There we really only need the 'join' feature, but doing things
* the same way allow us to name threads and similar stuff.
*/
/**
* Initializes the thread database.
*
* @returns iprt status code.
*/
int rtThreadInit(void)
{
#ifdef IN_RING3
int rc = VINF_ALREADY_INITIALIZED;
if (g_ThreadRWSem == NIL_RTSEMRW)
{
/*
* We assume the caller is the 1st thread, which we'll call 'main'.
* But first, we'll create the semaphore.
*/
if (RT_SUCCESS(rc))
{
rc = rtThreadNativeInit();
if (RT_SUCCESS(rc))
if (RT_SUCCESS(rc))
if (RT_SUCCESS(rc))
return VINF_SUCCESS;
/* failed, clear out */
}
}
/*
* Create the spinlock and to native init.
*/
if (RT_SUCCESS(rc))
{
rc = rtThreadNativeInit();
if (RT_SUCCESS(rc))
return VINF_SUCCESS;
/* failed, clear out */
}
#else
# error "!IN_RING0 && !IN_RING3"
#endif
return rc;
}
/**
* Terminates the thread database.
*/
void rtThreadTerm(void)
{
#ifdef IN_RING3
/* we don't cleanup here yet */
/* just destroy the spinlock and assume the thread is fine... */
if (g_ThreadTree != NULL)
#endif
}
#ifdef IN_RING3
DECLINLINE(void) rtThreadLockRW(void)
{
if (g_ThreadRWSem == NIL_RTSEMRW)
rtThreadInit();
}
DECLINLINE(void) rtThreadLockRD(void)
{
if (g_ThreadRWSem == NIL_RTSEMRW)
rtThreadInit();
}
DECLINLINE(void) rtThreadUnLockRW(void)
{
}
DECLINLINE(void) rtThreadUnLockRD(void)
{
}
#endif /* IN_RING3 */
/**
* Adopts the calling thread.
* No locks are taken or released by this function.
*/
static int rtThreadAdopt(RTTHREADTYPE enmType, unsigned fFlags, uint32_t fIntFlags, const char *pszName)
{
/*
* Allocate and insert the thread.
* (It is vital that rtThreadNativeAdopt updates the TLS before
* we try inserting the thread because of locking.)
*/
int rc = VERR_NO_MEMORY;
PRTTHREADINT pThread = rtThreadAlloc(enmType, fFlags, RTTHREADINT_FLAGS_ALIEN | fIntFlags, pszName);
if (pThread)
{
if (RT_SUCCESS(rc))
{
}
}
return rc;
}
/**
* Adopts a non-IPRT thread.
*
* @returns IPRT status code.
* @param enmType The thread type.
* @param fFlags The thread flags. RTTHREADFLAGS_WAITABLE is not currently allowed.
* @param pszName The thread name. Optional.
* @param pThread Where to store the thread handle. Optional.
*/
RTDECL(int) RTThreadAdopt(RTTHREADTYPE enmType, unsigned fFlags, const char *pszName, PRTTHREAD pThread)
{
int rc = VINF_SUCCESS;
if (Thread == NIL_RTTHREAD)
{
/* generate a name if none was given. */
char szName[RTTHREAD_NAME_LEN];
{
static uint32_t s_i32AlienId = 0;
}
/* try adopt it */
Thread = RTThreadSelf();
Log(("RTThreadAdopt: %RTthrd %RTnthrd '%s' enmType=%d fFlags=%#x rc=%Rrc\n",
}
else
Log(("RTThreadAdopt: %RTthrd %RTnthrd '%s' enmType=%d fFlags=%#x - already adopted!\n",
if (pThread)
return rc;
}
/**
* Get the thread handle of the current thread, automatically adopting alien
* threads.
*
* @returns Thread handle.
*/
{
return hSelf;
}
/**
* Allocates a per thread data structure and initializes the basic fields.
*
* @returns Pointer to per thread data structure.
* This is reference once.
* @returns NULL on failure.
* @param enmType The thread type.
* @param fFlags The thread flags.
* @param fIntFlags The internal thread flags.
* @param pszName Pointer to the thread name.
*/
PRTTHREADINT rtThreadAlloc(RTTHREADTYPE enmType, unsigned fFlags, uint32_t fIntFlags, const char *pszName)
{
if (pThread)
{
if (cchName >= RTTHREAD_NAME_LEN)
pThread->fReallySleeping = false;
#ifdef IN_RING3
#endif
if (RT_SUCCESS(rc))
{
if (RT_SUCCESS(rc))
return pThread;
}
}
return NULL;
}
/**
* Insert the per thread data structure into the tree.
*
* This can be called from both the thread it self and the parent,
* thus it must handle insertion failures in a nice manner.
*
* @param pThread Pointer to thread structure allocated by rtThreadAlloc().
* @param NativeThread The native thread id.
*/
{
/*
* Do not insert a terminated thread.
*
* This may happen if the thread finishes before the RTThreadCreate call
* gets this far. Since the OS may quickly reuse the native thread ID
* it should not be reinserted at this point.
*/
{
/*
* Before inserting we must check if there is a thread with this id
* in the tree already. We're racing parent and child on insert here
* so that the handle is valid in both ends when they return / start.
*
* If it's not ourself we find, it's a dead alien thread and we will
* unlink it from the tree. Alien threads will be released at this point.
*/
if (pThreadOther != pThread)
{
/* remove dead alien if any */
if (pThreadOther)
{
AssertMsg(pThreadOther->fIntFlags & RTTHREADINT_FLAGS_ALIEN, ("%p:%s; %p:%s\n", pThread, pThread->szName, pThreadOther, pThreadOther->szName));
}
/* insert the thread */
AssertReleaseMsg(fRc, ("Lock problem? %p (%RTnthrd) %s\n", pThread, NativeThread, pThread->szName));
}
}
}
/**
* Removes the thread from the AVL tree, call owns the tree lock
* and has cleared the RTTHREADINT_FLAG_IN_TREE bit.
*
* @param pThread The thread to remove.
*/
{
#if !defined(RT_OS_OS2) /** @todo this asserts for threads created by NSPR */
AssertMsg(pThread2 == pThread, ("%p(%s) != %p (%p/%s)\n", pThread2, pThread2 ? pThread2->szName : "<null>",
#endif
}
/**
* Removes the thread from the AVL tree.
*
* @param pThread The thread to remove.
*/
{
}
/**
* Checks if a thread is alive or not.
*
* @returns true if the thread is alive (or we don't really know).
* @returns false if the thread has surely terminate.
*/
{
}
/**
* Gets a thread by it's native ID.
*
* @returns pointer to the thread structure.
* @returns NULL if not a thread IPRT knows.
* @param NativeThread The native thread id.
*/
{
/*
* Simple tree lookup.
*/
return pThread;
}
/**
* Gets the per thread data structure for a thread handle.
*
* @returns Pointer to the per thread data structure for Thread.
* The caller must release the thread using rtThreadRelease().
* @returns NULL if Thread was not found.
* @param Thread Thread id which structure is to be returned.
*/
{
if ( Thread != NIL_RTTHREAD
{
{
return pThread;
}
}
return NULL;
}
/**
* Release a per thread data structure.
*
* @returns New reference count.
* @param pThread The thread structure to release.
*/
{
{
if (!cRefs)
}
else
cRefs = 0;
return cRefs;
}
/**
* Destroys the per thread data.
*
* @param pThread The thread to destroy.
*/
{
/*
* Remove it from the tree and mark it as dead.
*
* Threads that has seen rtThreadTerminate and should already have been
* removed from the tree. There is probably no thread that should
* require removing here. However, be careful making sure that cRefs
* isn't 0 if we do or we'll blow up because the strict locking code
* will be calling us back.
*/
{
}
/*
* Invalidate the thread structure and free it.
*/
#ifdef IN_RING3
#endif
#ifdef IN_RING3
#endif
/*
* Destroy semaphore resources.
*/
if (hEvt2 != NIL_RTSEMEVENTMULTI)
}
/**
* Terminates the thread.
* Called by the thread wrapper function when the thread terminates.
*
* @param pThread The thread structure.
* @param rc The thread result code.
*/
{
#ifdef IPRT_WITH_GENERIC_TLS
/*
* Destroy TLS entries.
*/
#endif /* IPRT_WITH_GENERIC_TLS */
/*
* Set the rc, mark it terminated and signal anyone waiting.
*/
/*
* Remove the thread from the tree so that there will be no
* key clashes in the AVL tree and release our reference to ourself.
*/
}
/**
* The common thread main function.
* This is called by rtThreadNativeMain().
*
* @returns The status code of the thread.
* pThread is dereference by the thread before returning!
* @param pThread The thread structure.
* @param NativeThread The native thread id.
* @param pszThreadName The name of the thread (purely a dummy for backtrace).
*/
{
Log(("rtThreadMain: Starting: pThread=%p NativeThread=%RTnthrd Name=%s pfnThread=%p pvUser=%p\n",
/*
* Change the priority.
*/
#ifdef IN_RING3
AssertMsgRC(rc, ("Failed to set priority of thread %p (%RTnthrd / %s) to enmType=%d enmPriority=%d rc=%Rrc\n",
#else
#endif
/*
* Call thread function and terminate when it returns.
*/
/*
* Paranoia checks for leftover resources.
*/
#ifdef RTSEMRW_STRICT
#endif
Log(("rtThreadMain: Terminating: rc=%d pThread=%p NativeThread=%RTnthrd Name=%s pfnThread=%p pvUser=%p\n",
return rc;
}
/**
* Create a new thread.
*
* @returns iprt status code.
* @param pThread Where to store the thread handle to the new thread. (optional)
* @param pfnThread The thread function.
* @param pvUser User argument.
* @param cbStack The size of the stack for the new thread.
* Use 0 for the default stack size.
* @param enmType The thread type. Used for deciding scheduling attributes
* of the thread.
* @param fFlags Flags of the RTTHREADFLAGS type (ORed together).
* @param pszName Thread name.
*/
{
LogFlow(("RTThreadCreate: pThread=%p pfnThread=%p pvUser=%p cbStack=%#x enmType=%d fFlags=%#x pszName=%p:{%s}\n",
/*
* Validate input.
*/
{
return VERR_INVALID_PARAMETER;
}
{
return VERR_INVALID_PARAMETER;
}
{
AssertMsgFailed(("pszName=%s (max len is %d because of logging)\n", pszName, RTTHREAD_NAME_LEN - 1));
return VERR_INVALID_PARAMETER;
}
if (fFlags & ~RTTHREADFLAGS_MASK)
{
return VERR_INVALID_PARAMETER;
}
/*
* Allocate thread argument.
*/
int rc;
if (pThreadInt)
{
if (RT_SUCCESS(rc))
{
if (pThread)
*pThread = pThreadInt;
return VINF_SUCCESS;
}
}
else
return rc;
}
/**
* Create a new thread.
*
* Same as RTThreadCreate except the name is given in the RTStrPrintfV form.
*
* @returns iprt status code.
* @param pThread See RTThreadCreate.
* @param pfnThread See RTThreadCreate.
* @param pvUser See RTThreadCreate.
* @param cbStack See RTThreadCreate.
* @param enmType See RTThreadCreate.
* @param fFlags See RTThreadCreate.
* @param pszNameFmt Thread name format.
* @param va Format arguments.
*/
{
}
/**
* Create a new thread.
*
* Same as RTThreadCreate except the name is given in the RTStrPrintf form.
*
* @returns iprt status code.
* @param pThread See RTThreadCreate.
* @param pfnThread See RTThreadCreate.
* @param pvUser See RTThreadCreate.
* @param cbStack See RTThreadCreate.
* @param enmType See RTThreadCreate.
* @param fFlags See RTThreadCreate.
* @param pszNameFmt Thread name format.
* @param ... Format arguments.
*/
{
return rc;
}
/**
* Gets the native thread id of a IPRT thread.
*
* @returns The native thread id.
* @param Thread The IPRT thread.
*/
{
if (pThread)
{
return NativeThread;
}
return NIL_RTNATIVETHREAD;
}
/**
* Gets the IPRT thread of a native thread.
*
* @returns The IPRT thread handle
* @returns NIL_RTTHREAD if not a thread known to IPRT.
*/
{
if (pThread)
return pThread;
return NIL_RTTHREAD;
}
/**
* Gets the name of the current thread thread.
*
* @returns Pointer to readonly name string.
* @returns NULL on failure.
*/
RTDECL(const char *) RTThreadSelfName(void)
{
if (Thread != NIL_RTTHREAD)
{
if (pThread)
{
return szName;
}
}
return NULL;
}
/**
* Gets the name of a thread.
*
* @returns Pointer to readonly name string.
* @returns NULL on failure.
* @param Thread Thread handle of the thread to query the name of.
*/
{
if (Thread == NIL_RTTHREAD)
return NULL;
if (pThread)
{
return szName;
}
return NULL;
}
/**
* Sets the name of a thread.
*
* @returns iprt status code.
* @param Thread Thread handle of the thread to query the name of.
* @param pszName The thread name.
*/
{
/*
* Validate input.
*/
if (cchName >= RTTHREAD_NAME_LEN)
{
return VERR_INVALID_PARAMETER;
}
if (!pThread)
return VERR_INVALID_HANDLE;
/*
* Update the name.
*/
return VINF_SUCCESS;
}
/**
* Checks if the specified thread is the main thread.
*
* @returns true if it is, false if it isn't.
*
* @param hThread The thread handle.
*
* @remarks This function may not return the correct value when RTR3Init was
* called on a thread of the than the main one. This could for
* loaded at run time by a different thread.
*/
{
if (pThread)
{
return fRc;
}
return false;
}
/**
* Signal the user event.
*
* @returns iprt status code.
*/
{
int rc;
if (pThread)
{
}
else
return rc;
}
/**
* Wait for the user event, resume on interruption.
*
* @returns iprt status code.
* @param Thread The thread to wait for.
* @param cMillies The number of milliseconds to wait. Use RT_INDEFINITE_WAIT for
* an indefinite wait.
*/
{
int rc;
if (pThread)
{
}
else
return rc;
}
/**
* Wait for the user event, return on interruption.
*
* @returns iprt status code.
* @param Thread The thread to wait for.
* @param cMillies The number of milliseconds to wait. Use RT_INDEFINITE_WAIT for
* an indefinite wait.
*/
{
int rc;
if (pThread)
{
}
else
return rc;
}
/**
* Reset the user event.
*
* @returns iprt status code.
* @param Thread The thread to reset.
*/
{
int rc;
if (pThread)
{
}
else
return rc;
}
/**
* Wait for the thread to terminate.
*
* @returns iprt status code.
* @param Thread The thread to wait for.
* @param cMillies The number of milliseconds to wait. Use RT_INDEFINITE_WAIT for
* an indefinite wait.
* @param prc Where to store the return code of the thread. Optional.
* @param fAutoResume Whether or not to resume the wait on VERR_INTERRUPTED.
*/
{
int rc = VERR_INVALID_HANDLE;
if (Thread != NIL_RTTHREAD)
{
if (pThread)
{
{
if (fAutoResume)
else
if (RT_SUCCESS(rc))
{
if (prc)
/*
* If the thread is marked as waitable, we'll do one additional
* release in order to free up the thread structure (see how we
* init cRef in rtThreadAlloc()).
*/
}
}
else
{
}
}
}
return rc;
}
/**
* Wait for the thread to terminate, resume on interruption.
*
* @returns iprt status code.
* Will not return VERR_INTERRUPTED.
* @param Thread The thread to wait for.
* @param cMillies The number of milliseconds to wait. Use RT_INDEFINITE_WAIT for
* an indefinite wait.
* @param prc Where to store the return code of the thread. Optional.
*/
{
return rc;
}
/**
* Wait for the thread to terminate, return on interruption.
*
* @returns iprt status code.
* @param Thread The thread to wait for.
* @param cMillies The number of milliseconds to wait. Use RT_INDEFINITE_WAIT for
* an indefinite wait.
* @param prc Where to store the return code of the thread. Optional.
*/
{
}
/**
* Changes the type of the specified thread.
*
* @returns iprt status code.
* @param Thread The thread which type should be changed.
* @param enmType The new thread type.
*/
{
/*
* Validate input.
*/
int rc;
if ( enmType > RTTHREADTYPE_INVALID
&& enmType < RTTHREADTYPE_END)
{
if (pThread)
{
if (rtThreadIsAlive(pThread))
{
/*
* Do the job.
*/
if (RT_SUCCESS(rc))
if (RT_FAILURE(rc))
}
else
}
else
}
else
{
}
return rc;
}
/**
* Gets the type of the specified thread.
*
* @returns The thread type.
* @returns RTTHREADTYPE_INVALID if the thread handle is invalid.
* @param Thread The thread in question.
*/
{
if (pThread)
{
}
return enmType;
}
#ifdef IN_RING3
/**
* Recalculates scheduling attributes for the default process
* priority using the specified priority type for the calling thread.
*
* The scheduling attributes are targeted at threads and they are protected
* by the thread read-write semaphore, that's why RTProc is forwarding the
* operation to RTThread.
*
* @returns iprt status code.
* @remarks Will only work for strict builds.
*/
{
return rc;
}
/**
* Thread enumerator - sets the priority of one thread.
*
* @returns 0 to continue.
* @returns !0 to stop. In our case a VERR_ code.
* @param pNode The thread node.
* @param pvUser The new priority.
*/
{
if (!rtThreadIsAlive(pThread))
return VINF_SUCCESS;
return VINF_SUCCESS;
return rc;
}
/**
* Attempts to alter the priority of the current process.
*
* The scheduling attributes are targeted at threads and they are protected
* by the thread read-write semaphore, that's why RTProc is forwarding the
* operation to RTThread. This operation also involves updating all thread
* which is much faster done from RTThread.
*
* @returns iprt status code.
* @param enmPriority The new priority.
*/
{
/*
* First validate that we're allowed by the OS to use all the
* scheduling attributes defined by the specified process priority.
*/
if (RT_SUCCESS(rc))
{
/*
* Update the priority of existing thread.
*/
if (RT_SUCCESS(rc))
else
{
/*
* Failed, restore the priority.
*/
}
}
return rc;
}
/**
* Change the thread state to blocking.
*
* @param hThread The current thread.
* @param enmState The sleep state.
* @param fReallySleeping Really going to sleep now.
*/
{
if (pThread != NIL_RTTHREAD)
{
}
}
/**
* Unblocks a thread.
*
* This function is paired with rtThreadBlocking.
*
* @param hThread The current thread.
* @param enmCurState The current state, used to check for nested blocking.
* The new state will be running.
*/
{
if (pThread != NIL_RTTHREAD)
{
}
}
/**
* Get the current thread state.
*
* @returns The thread state.
* @param hThread The thread.
*/
{
if (pThread)
{
}
return enmState;
}
{
if (pThread)
{
}
return enmState;
}
/**
* Translate a thread state into a string.
*
* @returns Pointer to a read-only string containing the state name.
* @param enmState The state.
*/
{
switch (enmState)
{
case RTTHREADSTATE_INVALID: return "INVALID";
case RTTHREADSTATE_INITIALIZING: return "INITIALIZING";
case RTTHREADSTATE_TERMINATED: return "TERMINATED";
case RTTHREADSTATE_RUNNING: return "RUNNING";
case RTTHREADSTATE_CRITSECT: return "CRITSECT";
case RTTHREADSTATE_EVENT: return "EVENT";
case RTTHREADSTATE_EVENT_MULTI: return "EVENT_MULTI";
case RTTHREADSTATE_FAST_MUTEX: return "FAST_MUTEX";
case RTTHREADSTATE_MUTEX: return "MUTEX";
case RTTHREADSTATE_RW_READ: return "RW_READ";
case RTTHREADSTATE_RW_WRITE: return "RW_WRITE";
case RTTHREADSTATE_SLEEP: return "SLEEP";
case RTTHREADSTATE_SPIN_MUTEX: return "SPIN_MUTEX";
default: return "UnknownThreadState";
}
}
#endif /* IN_RING3 */
#ifdef IPRT_WITH_GENERIC_TLS
/**
* Thread enumerator - clears a TLS entry.
*
* @returns 0.
* @param pNode The thread node.
* @param pvUser The TLS index.
*/
{
return 0;
}
/**
* Helper for the generic TLS implementation that clears a given TLS
* entry on all threads.
*
* @param iTls The TLS entry. (valid)
*/
{
RTAvlPVDoWithAll(&g_ThreadTree, true /* fFromLeft*/, rtThreadClearTlsEntryCallback, (void *)(uintptr_t)iTls);
}
#endif /* IPRT_WITH_GENERIC_TLS */