/*  $Id: ncbithr.cpp 95296 2021-11-03 14:44:59Z grichenk $
 * ===========================================================================
 *
 *                            PUBLIC DOMAIN NOTICE
 *               National Center for Biotechnology Information
 *
 *  This software/database is a "United States Government Work" under the
 *  terms of the United States Copyright Act.  It was written as part of
 *  the author's official duties as a United States Government employee and
 *  thus cannot be copyrighted.  This software/database is freely available
 *  to the public for use. The National Library of Medicine and the U.S.
 *  Government have not placed any restriction on its use or reproduction.
 *
 *  Although all reasonable efforts have been taken to ensure the accuracy
 *  and reliability of the software and data, the NLM and the U.S.
 *  Government do not and cannot warrant the performance or results that
 *  may be obtained by using this software or data. The NLM and the U.S.
 *  Government disclaim all warranties, express or implied, including
 *  warranties of performance, merchantability or fitness for any particular
 *  purpose.
 *
 *  Please cite the author in any work or product based on this material.
 *
 * ===========================================================================
 *
 * Author:  Denis Vakatov, Aleksey Grichenko
 *
 * File Description:
 *   Multi-threading -- classes, functions, and features.
 *
 *    TLS:
 *      CTlsBase         -- TLS implementation (base class for CTls<>)
 *
 *    THREAD:
 *      CThread          -- thread wrapper class
 *
 *    RW-LOCK:
 *      CInternalRWLock  -- platform-dependent RW-lock structure (fwd-decl)
 *      CRWLock          -- Read/Write lock related  data and methods
 *
 */


#include <ncbi_pch.hpp>
#include <corelib/ncbi_param.hpp>
#include <corelib/request_ctx.hpp>
#include <corelib/ncbi_system.hpp>
#include <corelib/error_codes.hpp>
#ifdef NCBI_POSIX_THREADS
#  include <sys/time.h> // for gettimeofday()
#endif
#ifdef NCBI_OS_LINUX
#  include <sys/prctl.h>
#endif

#include "ncbidbg_p.hpp"


#define NCBI_USE_ERRCODE_X   Corelib_Threads

BEGIN_NCBI_SCOPE


/////////////////////////////////////////////////////////////////////////////
//  CTlsBase::
//


DEFINE_STATIC_MUTEX(s_TlsCleanupMutex);


CUsedTlsBases::CUsedTlsBases(void)
{
}


CUsedTlsBases::~CUsedTlsBases(void)
{
}


void CUsedTlsBases::ClearAll(CTlsBase::ECleanupMode mode)
{
    CMutexGuard tls_cleanup_guard(s_TlsCleanupMutex);
    // Prevent double-destruction
    CTlsBase* used_tls = NULL;
    NON_CONST_ITERATE(TTlsSet, it, m_UsedTls) {
        CTlsBase* tls = *it;
        // Do not cleanup it now - this will cause infinite recursion
        if (tls == &sm_UsedTlsBases.Get()) {
            used_tls = tls;
            continue;
        }
        // Prevent double-destruction
        tls->x_DeleteTlsData(mode);
        if (tls->m_AutoDestroy  &&  tls->Referenced()) {
            tls->RemoveReference();
        }
    }
    m_UsedTls.clear();

    if (used_tls) {
        used_tls->x_DeleteTlsData(mode);
        if (used_tls->m_AutoDestroy  &&  used_tls->Referenced()) {
            used_tls->RemoveReference();
        }
    }
}


void CUsedTlsBases::Register(CTlsBase* tls)
{
    CMutexGuard tls_cleanup_guard(s_TlsCleanupMutex);
    if ( m_UsedTls.insert(tls).second ) {
        if (tls->m_AutoDestroy) {
            tls->AddReference();
        }
    }
}


void CUsedTlsBases::Deregister(CTlsBase* tls)
{
    CMutexGuard tls_cleanup_guard(s_TlsCleanupMutex);
    xncbi_VerifyAndErrorReport(m_UsedTls.erase(tls));
    if (tls->m_AutoDestroy) {
        tls->RemoveReference();
    }
}


static void s_CleanupUsedTlsBases(CUsedTlsBases* tls, void*)
{
    delete tls;
}

static void s_CleanupMainUsedTlsBases(CUsedTlsBases& tls)
{
    tls.ClearAll();
}

// Storage for used TLS sets
CStaticTls<CUsedTlsBases>
    CUsedTlsBases::sm_UsedTlsBases(0, CSafeStaticLifeSpan::eLifeSpan_Long);
// Main thread needs a usual safe-static-ref for proper cleanup --
// there's no thread which can do it on destruction.
static CSafeStatic<CUsedTlsBases>
s_MainUsedTlsBases(0, s_CleanupMainUsedTlsBases,
CSafeStaticLifeSpan::eLifeSpan_Long);

CUsedTlsBases& CUsedTlsBases::GetUsedTlsBases(void)
{
    if ( CThread::IsMain() )
    {
        return *s_MainUsedTlsBases;
    }

    CUsedTlsBases* tls = sm_UsedTlsBases.GetValue();
    if ( !tls )
    {
        tls = new CUsedTlsBases();
        sm_UsedTlsBases.SetValue(tls, s_CleanupUsedTlsBases, nullptr, CTlsBase::eDoCleanup);
    }
    return *tls;
}


void CUsedTlsBases::Init(void)
{
    sm_UsedTlsBases.Get();
}


void CUsedTlsBases::ClearAllCurrentThread(CTlsBase::ECleanupMode mode)
{
    if ( CUsedTlsBases* tls = sm_UsedTlsBases.GetValue() ) {
        tls->ClearAll(mode);
    }
}


struct SNativeThreadTlsCleanup
{
    ~SNativeThreadTlsCleanup(void) {
        if ( CThread::IsMain() ) return;
        CUsedTlsBases::ClearAllCurrentThread(CTlsBase::eCleanup_Native);
    }
};


void CTlsBase::CleanupTlsData(void* data, ECleanupMode mode)
{
    if (!data) return;
    STlsData* tls_data = static_cast<STlsData*>(data);
    if (!tls_data->m_Value || !tls_data->m_CleanupFunc) return;
    if (mode == eCleanup_Native && tls_data->m_Native == eSkipCleanup) return;
    tls_data->m_CleanupFunc(tls_data->m_Value, tls_data->m_CleanupData);
}


void CTlsBase::CleanupAndDeleteTlsData(void* data, ECleanupMode mode)
{
    if (!data) return;
    STlsData* tls_data = static_cast<STlsData*>(data);
    CleanupTlsData(data, mode);
    delete tls_data;
}


void CTlsBase::x_CleanupThreadCallback(void* ptr)
{
    CTlsBase::CleanupAndDeleteTlsData(ptr);
}


void CTlsBase::x_Init(void)
{
    // Create platform-dependent TLS key (index)
#if defined(NCBI_WIN32_THREADS)
    xncbi_VerifyAndErrorReport((m_Key = TlsAlloc()) != DWORD(-1));
#elif defined(NCBI_POSIX_THREADS)
    xncbi_VerifyAndErrorReport(pthread_key_create(&m_Key, x_CleanupThreadCallback) == 0);
    // pthread_key_create does not reset the value to 0 if the key has been
    // used and deleted.
    xncbi_VerifyAndErrorReport(pthread_setspecific(m_Key, 0) == 0);
#else
    m_Key = 0;
#endif

    m_Initialized = true;
}


void CTlsBase::x_Destroy(void)
{
    x_Reset();
    m_Initialized = false;

    // Destroy system TLS key
#if defined(NCBI_WIN32_THREADS)
    if ( TlsFree(m_Key) ) {
        m_Key = 0;
        return;
    }
    assert(0);
#elif defined(NCBI_POSIX_THREADS)
    if (pthread_key_delete(m_Key) == 0) {
        m_Key = 0;
        return;
    }
    assert(0);
#else
    m_Key = 0;
    return;
#endif
}


// Platform-specific TLS data storing
inline
void s_TlsSetValue(TTlsKey& key, void* data, const char* err_message)
{
#if defined(NCBI_WIN32_THREADS)
    xncbi_Validate(TlsSetValue(key, data), err_message);
#elif defined(NCBI_POSIX_THREADS)
    xncbi_ValidatePthread(pthread_setspecific(key, data), 0, err_message);
#else
    key = data;
    assert(err_message);  // to get rid of the "unused variable" warning
#endif
}


void CTlsBase::x_SetValue(void*        value,
                          FCleanupBase cleanup,
                          void*        cleanup_data,
                          ENativeThreadCleanup native)
{
    if ( !m_Initialized ) {
        return;
    }

    // Get previously stored data
    STlsData* tls_data = static_cast<STlsData*> (x_GetTlsData());

    // Create and initialize TLS structure, if it was not present
    if ( !tls_data ) {
        tls_data = new STlsData;
        xncbi_Validate(tls_data != 0,
                       "CTlsBase::x_SetValue() -- cannot allocate "
                       "memory for TLS data");
        tls_data->m_Value       = 0;
        tls_data->m_CleanupFunc = 0;
        tls_data->m_CleanupData = 0;
        tls_data->m_Native = eSkipCleanup;

#ifdef NCBI_WIN32_THREADS
        static thread_local SNativeThreadTlsCleanup s_NativeThreadTlsCleanup;
#endif
    }

    // Cleanup
    if (tls_data->m_Value != value) {
        CleanupTlsData(tls_data);
    }

    // Store the values
    tls_data->m_Value       = value;
    tls_data->m_CleanupFunc = cleanup;
    tls_data->m_CleanupData = cleanup_data;
    tls_data->m_Native = native;

    // Store the structure in the TLS
    s_TlsSetValue(m_Key, tls_data,
                  "CTlsBase::x_SetValue() -- error setting value");

    // Add to the used TLS list to cleanup data in the thread Exit()
    CUsedTlsBases::GetUsedTlsBases().Register(this);
}


bool CTlsBase::x_DeleteTlsData(ECleanupMode mode)
{
    if ( !m_Initialized ) {
        return false;
    }

    // Get previously stored data
    STlsData* tls_data = static_cast<STlsData*> (x_GetTlsData());
    if ( !tls_data ) {
        return false;
    }

    // Cleanup & destroy
    CleanupAndDeleteTlsData(tls_data, mode);

    // Store NULL in the TLS
    s_TlsSetValue(m_Key, 0,
                  "CTlsBase::x_Reset() -- error cleaning-up TLS");

    return true;
}


void CTlsBase::x_Reset(void)
{
    if ( x_DeleteTlsData() ) {
        // Deregister this TLS from the current thread
        CUsedTlsBases::GetUsedTlsBases().Deregister(this);
    }
}


/////////////////////////////////////////////////////////////////////////////
//  CExitThreadException::
//
//    Exception used to terminate threads safely, cleaning up
//    all the resources allocated.
//


class CExitThreadException
{
public:
    // Create new exception object, initialize counter.
    CExitThreadException(void);

    // Create a copy of exception object, increase counter.
    CExitThreadException(const CExitThreadException& prev);

    // Destroy the object, decrease counter. If the counter is
    // zero outside of CThread::Wrapper(), rethrow exception.
    ~CExitThreadException(void);

    // Inform the object it has reached CThread::Wrapper().
    void EnterWrapper(void)
    {
        *m_InWrapper = true;
    }
private:
    int* m_RefCount;
    bool* m_InWrapper;
};


CExitThreadException::CExitThreadException(void)
    : m_RefCount(new int),
      m_InWrapper(new bool)
{
    *m_RefCount = 1;
    *m_InWrapper = false;
}


CExitThreadException::CExitThreadException(const CExitThreadException& prev)
    : m_RefCount(prev.m_RefCount),
      m_InWrapper(prev.m_InWrapper)
{
    (*m_RefCount)++;
}


CExitThreadException::~CExitThreadException(void)
{
    if (--(*m_RefCount) > 0) {
        // Not the last object - continue to handle exceptions
        return;
    }

    bool tmp_in_wrapper = *m_InWrapper; // save the flag
    delete m_RefCount;
    delete m_InWrapper;

    if ( !tmp_in_wrapper ) {
        // Something is wrong - terminate the thread
        assert(((void)("CThread::Exit() -- cannot exit thread"), 0));
#if defined(NCBI_WIN32_THREADS)
        ExitThread(0);
#elif defined(NCBI_POSIX_THREADS)
        pthread_exit(0);
#endif
    }

}



/////////////////////////////////////////////////////////////////////////////
//  CThread::
//

// Mutex to protect CThread members and to make sure that Wrapper() function
// will not proceed until after the appropriate Run() is finished.
DEFINE_STATIC_FAST_MUTEX(s_ThreadMutex);

atomic<unsigned int> CThread::sm_ThreadsCount(0);


// Internal storage for thread objects and related variables/functions
static DECLARE_TLS_VAR(CThread*, sx_ThreadPtr);
static DECLARE_TLS_VAR(CThread::TID, sx_ThreadId);
static bool sm_MainThreadIdInitialized = false;
static const CThread::TID kMainThreadId = ~CThread::TID(0);
static CThread::TID sx_MainThreadId = kMainThreadId;


DEFINE_STATIC_FAST_MUTEX(s_MainThreadIdMutex);

CThread::TID sx_GetMainThreadId()
{
    CFastMutexGuard guard(s_MainThreadIdMutex);
    return sx_MainThreadId;
}


void sx_SetMainThreadId(CThread::TID id)
{
    CFastMutexGuard guard(s_MainThreadIdMutex);
    sx_MainThreadId = id;
}


static int sx_GetNextThreadId(void)
{
    CFastMutexGuard guard(s_ThreadMutex);
    static int s_ThreadCount = 0;
    return ++s_ThreadCount;
}


void CThread::x_InitializeThreadId(void)
{
#if defined(NCBI_THREADS)
    _ASSERT(!sx_ThreadPtr);
    _ASSERT(!sx_ThreadId);
#endif
    sx_ThreadPtr = this;
    sx_ThreadId = sx_GetNextThreadId();
}


void CThread::InitializeMainThreadId(void)
{
    // mark main thread
#if defined(NCBI_THREADS)
    CFastMutexGuard guard(s_MainThreadIdMutex);
#endif
    if ( sm_MainThreadIdInitialized ) {
        if (sx_ThreadId != sx_MainThreadId) {
            ERR_POST("Can not change main thread ID");
        }
        return;
    }
#if defined(NCBI_THREADS)
    _ASSERT(!sx_ThreadPtr);
    _ASSERT(sx_MainThreadId == kMainThreadId);
#endif
    if ( !sx_ThreadId ) {
        // Not yet assigned - use the default value.
        sx_ThreadId = kMainThreadId;
    }
    sx_MainThreadId = sx_ThreadId;
    sx_ThreadPtr = 0;
    sm_MainThreadIdInitialized = true;
}


CThread* CThread::GetCurrentThread(void)
{
    // Get pointer to the current thread object
    return sx_ThreadPtr;
}


CThread::TID CThread::GetSelf(void)
{
    TID id = sx_ThreadId;
    if ( !id ) {
        // If main thread has not been set, consider current thread is the main one.
        // Since sx_ThreadId is still zero, InitializeMainThreadId() will set it to
        // kMainThreadId, so that the value returned by GetSelf() will be zero.
        if (!sm_MainThreadIdInitialized) {
            InitializeMainThreadId();
            id = sx_ThreadId;
        }
        else {
            sx_ThreadId = id = sx_GetNextThreadId();
        }
    }
    // kMainThreadId is usually marker for main thread, but when using native threads
    // and InitializeMainThreadId() to set main thread, the main thread id may be
    // different and it's more reliable to use IsMain() rather than GetSelf() == 0.
    return id == kMainThreadId ? 0 : id;
}


bool CThread::IsMain(void)
{
    if (!sm_MainThreadIdInitialized) {
        InitializeMainThreadId();
    }
    return sx_ThreadId == sx_GetMainThreadId();
}


NCBI_PARAM_DECL(bool, Thread, Catch_Unhandled_Exceptions);
NCBI_PARAM_DEF_EX(bool, Thread, Catch_Unhandled_Exceptions, true, 0,
                  THREAD_CATCH_UNHANDLED_EXCEPTIONS);
typedef NCBI_PARAM_TYPE(Thread, Catch_Unhandled_Exceptions) TParamThreadCatchExceptions;


TWrapperRes CThread::Wrapper(TWrapperArg arg)
{
    // Get thread object and self ID
    CThread* thread_obj = static_cast<CThread*>(arg);

    // Set Toolkit thread ID.
    thread_obj->x_InitializeThreadId();
    xncbi_Validate(!IsMain(),
                   "CThread::Wrapper() -- error assigning thread ID");

#if defined NCBI_THREAD_PID_WORKAROUND
    // Store this thread's PID. Changed PID means forking of the thread.
    thread_obj->m_ThreadPID =
        CProcess::sx_GetPid(CProcess::ePID_GetThread);
#endif

    bool catch_all = TParamThreadCatchExceptions::GetDefault();

    // Check if parent request context should be used.
    if ( thread_obj->m_ParentRequestContext ) {
        CDiagContext::SetRequestContext(thread_obj->m_ParentRequestContext);
    }

    // Run user-provided thread main function here
    if ( catch_all ) {
        try {
            thread_obj->m_ExitData = thread_obj->Main();
        }
        catch (CExitThreadException& e) {
            e.EnterWrapper();
        }
#if defined(NCBI_COMPILER_MSVC)  &&  defined(_DEBUG)
        // Microsoft promotes many common application errors to exceptions.
        // This includes occurrences such as dereference of a NULL pointer and
        // walking off of a dangling pointer.  The catch-all is lifted only in
        // debug mode to permit easy inspection of such error conditions, while
        // maintaining safety of production, release-mode applications.
        NCBI_CATCH_X(1, "CThread::Wrapper: CThread::Main() failed");
#else
        NCBI_CATCH_ALL_X(2, "CThread::Wrapper: CThread::Main() failed");
#endif
    }
    else {
        try {
            thread_obj->m_ExitData = thread_obj->Main();
        }
        catch (CExitThreadException& e) {
            e.EnterWrapper();
        }
    }

    // Call user-provided OnExit()
    if ( catch_all ) {
        try {
            thread_obj->OnExit();
        }
#if defined(NCBI_COMPILER_MSVC)  &&  defined(_DEBUG)
        // Microsoft promotes many common application errors to exceptions.
        // This includes occurrences such as dereference of a NULL pointer and
        // walking off of a dangling pointer.  The catch-all is lifted only in
        // debug mode to permit easy inspection of such error conditions, while
        // maintaining safety of production, release-mode applications.
        NCBI_CATCH_X(3, "CThread::Wrapper: CThread::OnExit() failed");
#else
        NCBI_CATCH_ALL_X(4, "CThread::Wrapper: CThread::OnExit() failed");
#endif
    }
    else {
        thread_obj->OnExit();
    }

    // Cleanup local storages used by this thread
    CUsedTlsBases::ClearAllCurrentThread();

    {{
        CFastMutexGuard state_guard(s_ThreadMutex);

        // Thread is terminated - decrement counter under mutex
        --sm_ThreadsCount;

        // Indicate the thread is terminated
        thread_obj->m_IsTerminated = true;

        // Schedule the thread object for destruction, if detached
        if ( thread_obj->m_IsDetached ) {
            thread_obj->m_SelfRef.Reset();
        }
    }}

    return 0;
}


CThread::CThread(void)
    : m_Handle(0), m_IsRun(false),
      m_IsDetached(false),
      m_IsJoined(false),
      m_IsTerminated(false),
      m_ExitData(0)
#if defined NCBI_THREAD_PID_WORKAROUND
      , m_ThreadPID(0)
#endif
{
    DoDeleteThisObject();
}


CThread::~CThread(void)
{
#if defined(NCBI_WIN32_THREADS)
    // close handle if it's not yet closed
//    CFastMutexGuard state_guard(s_ThreadMutex);
    if ( m_IsRun && m_Handle != NULL ) {
        CloseHandle(m_Handle);
        m_Handle = NULL;
    }
#endif
}



inline TWrapperRes ThreadWrapperCaller(TWrapperArg arg) {
    return CThread::Wrapper(arg);
}

#if defined(NCBI_POSIX_THREADS)
extern "C" {
    typedef TWrapperRes (*FSystemWrapper)(TWrapperArg);

    static TWrapperRes ThreadWrapperCallerImpl(TWrapperArg arg) {
        return ThreadWrapperCaller(arg);
    }
}
#elif defined(NCBI_WIN32_THREADS)
extern "C" {
    typedef TWrapperRes (WINAPI *FSystemWrapper)(TWrapperArg);

    static TWrapperRes WINAPI ThreadWrapperCallerImpl(TWrapperArg arg) {
        return ThreadWrapperCaller(arg);
    }
}
#endif


#if defined NCBI_THREAD_PID_WORKAROUND
TPid CThread::sx_GetThreadPid(void)
{
    CThread* thread_ptr = GetCurrentThread();
    return thread_ptr ? thread_ptr->m_ThreadPID : 0;
}


void CThread::sx_SetThreadPid(TPid pid)
{
    CThread* thread_ptr = GetCurrentThread();
    if ( thread_ptr ) {
        thread_ptr->m_ThreadPID = pid;
    }
}
#endif


#define NCBI_THREAD_VALIDATE(cond, error_code, message) \
    if ( !(cond) ) NCBI_THROW(CThreadException, error_code, message)


// Stack size parameter, 2M by default.
NCBI_PARAM_DECL(size_t, Thread, StackSize);
NCBI_PARAM_DEF_EX(size_t, Thread, StackSize, 2048*1024, eParam_NoThread, THREAD_STACK_SIZE);
typedef NCBI_PARAM_TYPE(Thread, StackSize) TParamThreadStackSize;


bool CThread::Run(TRunMode flags)
{
    CUsedTlsBases::Init();

    // Do not allow the new thread to run until m_Handle is set
    CFastMutexGuard state_guard(s_ThreadMutex);

    // Check
    NCBI_THREAD_VALIDATE(!m_IsRun, eRunError,
        "CThread::Run() -- called for already started thread");

    m_IsDetached = (flags & fRunDetached) != 0;

#if defined NCBI_THREAD_PID_WORKAROUND
    CProcess::sx_GetPid(CProcess::ePID_GetCurrent);
#endif

    // Thread will run - increment counter under mutex
    ++sm_ThreadsCount;
    try {

        if (flags & fRunCloneRequestContext) {
            m_ParentRequestContext = CDiagContext::GetRequestContext().Clone();
        }

#if defined(NCBI_WIN32_THREADS)
        // We need this parameter in WinNT - can not use NULL instead!
        DWORD thread_id;
        // Suspend thread to adjust its priority
        DWORD creation_flags = (flags & fRunNice) == 0 ? 0 : CREATE_SUSPENDED;
        m_Handle = CreateThread(NULL, 0, ThreadWrapperCallerImpl,
                                this, creation_flags, &thread_id);
        NCBI_THREAD_VALIDATE(m_Handle != NULL, eRunError,
            "CThread::Run() -- error creating thread");
        if (flags & fRunNice) {
            // Adjust priority and resume the thread
            SetThreadPriority(m_Handle, THREAD_PRIORITY_BELOW_NORMAL);
            ResumeThread(m_Handle);
        }
        if ( m_IsDetached ) {
            CloseHandle(m_Handle);
            m_Handle = NULL;
        }
        else {
            // duplicate handle to adjust security attributes
            HANDLE oldHandle = m_Handle;
            NCBI_THREAD_VALIDATE(DuplicateHandle(GetCurrentProcess(), oldHandle,
                GetCurrentProcess(), &m_Handle,
                0, FALSE, DUPLICATE_SAME_ACCESS),
                eRunError, "CThread::Run() -- error getting thread handle");
            NCBI_THREAD_VALIDATE(CloseHandle(oldHandle),
                eRunError, "CThread::Run() -- error closing thread handle");
        }
#elif defined(NCBI_POSIX_THREADS)
        pthread_attr_t attr;
        NCBI_THREAD_VALIDATE(pthread_attr_init(&attr) == 0, eRunError,
            "CThread::Run() - error initializing thread attributes");
        if ( ! (flags & fRunUnbound) ) {
#if defined(NCBI_OS_BSD)  ||  defined(NCBI_OS_CYGWIN)  ||  defined(NCBI_OS_IRIX)
            NCBI_THREAD_VALIDATE(pthread_attr_setscope(&attr,
                PTHREAD_SCOPE_PROCESS) == 0, eRunError,
                "CThread::Run() - error setting thread scope");
#else
            NCBI_THREAD_VALIDATE(pthread_attr_setscope(&attr,
                PTHREAD_SCOPE_SYSTEM) == 0, eRunError,
                "CThread::Run() - error setting thread scope");
#endif
        }
        if ( m_IsDetached ) {
            NCBI_THREAD_VALIDATE(pthread_attr_setdetachstate(&attr,
                PTHREAD_CREATE_DETACHED) == 0, eRunError,
                "CThread::Run() - error setting thread detach state");
        }
        NCBI_THREAD_VALIDATE(pthread_attr_setstacksize(&attr,
            TParamThreadStackSize::GetDefault()) == 0, eRunError,
            "Thread::Run() -- error setting stack size");
        NCBI_THREAD_VALIDATE(pthread_create(&m_Handle, &attr,
            ThreadWrapperCallerImpl, this) == 0, eRunError,
            "CThread::Run() -- error creating thread");

        NCBI_THREAD_VALIDATE(pthread_attr_destroy(&attr) == 0, eRunError,
            "CThread::Run() - error destroying thread attributes");

#else
        if (flags & fRunAllowST) {
            Wrapper(this);
        }
        else {
            NCBI_THREAD_VALIDATE(0, eRunError,
                "CThread::Run() -- system does not support threads");
        }
#endif

        // prevent deletion of CThread until thread is finished
        m_SelfRef.Reset(this);

    }
    catch (...) {
        // In case of any error we need to decrement threads count
        --sm_ThreadsCount;
        throw;
    }

    // Indicate that the thread is run
    m_IsRun = true;
    return true;
}


void CThread::Detach(void)
{
    CFastMutexGuard state_guard(s_ThreadMutex);

    // Check the thread state: it must be run, but not detached yet
    NCBI_THREAD_VALIDATE(m_IsRun, eControlError,
        "CThread::Detach() -- called for not yet started thread");
    NCBI_THREAD_VALIDATE(!m_IsDetached, eControlError,
        "CThread::Detach() -- called for already detached thread");

    // Detach the thread
#if defined(NCBI_WIN32_THREADS)
    NCBI_THREAD_VALIDATE(CloseHandle(m_Handle), eControlError,
        "CThread::Detach() -- error closing thread handle");
    m_Handle = NULL;
#elif defined(NCBI_POSIX_THREADS)
    NCBI_THREAD_VALIDATE(pthread_detach(m_Handle) == 0, eControlError,
        "CThread::Detach() -- error detaching thread");
#endif

    // Indicate the thread is detached
    m_IsDetached = true;

    // Schedule the thread object for destruction, if already terminated
    if ( m_IsTerminated ) {
        m_SelfRef.Reset();
    }
}


void CThread::Join(void** exit_data)
{
    // Check the thread state: it must be run, but not detached yet
    {{
        CFastMutexGuard state_guard(s_ThreadMutex);
        NCBI_THREAD_VALIDATE(m_IsRun, eControlError,
            "CThread::Join() -- called for not yet started thread");
        NCBI_THREAD_VALIDATE(!m_IsDetached, eControlError,
            "CThread::Join() -- called for detached thread");
        NCBI_THREAD_VALIDATE(!m_IsJoined, eControlError,
            "CThread::Join() -- called for already joined thread");
        m_IsJoined = true;
    }}

    // Join (wait for) and destroy
#if defined(NCBI_WIN32_THREADS)
    NCBI_THREAD_VALIDATE(WaitForSingleObject(m_Handle, INFINITE) == WAIT_OBJECT_0,
        eControlError, "CThread::Join() -- can not join thread");
    DWORD status;
    NCBI_THREAD_VALIDATE(GetExitCodeThread(m_Handle, &status) &&
        status != DWORD(STILL_ACTIVE), eControlError,
        "CThread::Join() -- thread is still running after join");
    NCBI_THREAD_VALIDATE(CloseHandle(m_Handle), eControlError,
        "CThread::Join() -- can not close thread handle");
    m_Handle = NULL;
#elif defined(NCBI_POSIX_THREADS)
    NCBI_THREAD_VALIDATE(pthread_join(m_Handle, 0) == 0, eControlError,
        "CThread::Join() -- can not join thread");
#endif

    // Set exit_data value
    if ( exit_data ) {
        *exit_data = m_ExitData;
    }

    // Schedule the thread object for destruction
    {{
        CFastMutexGuard state_guard(s_ThreadMutex);
        m_SelfRef.Reset();
    }}
}


void CThread::Exit(void* exit_data)
{
    // Don't exit from the main thread
    CThread* x_this = GetCurrentThread();
    NCBI_THREAD_VALIDATE(x_this != 0, eControlError,
        "CThread::Exit() -- attempt to call for the main thread");

    {{
        CFastMutexGuard state_guard(s_ThreadMutex);
        x_this->m_ExitData = exit_data;
    }}

    // Throw the exception to be caught by Wrapper()
    throw CExitThreadException();
}


bool CThread::Discard(void)
{
    CFastMutexGuard state_guard(s_ThreadMutex);

    // Do not discard after Run()
    if ( m_IsRun ) {
        return false;
    }

    // Schedule for destruction (or, destroy it right now if there is no
    // other CRef<>-based references to this object left).
    m_SelfRef.Reset(this);
    m_SelfRef.Reset();
    return true;
}


void CThread::OnExit(void)
{
    return;
}


void CThread::GetSystemID(TThreadSystemID* id)
{
    *id = GetCurrentThreadSystemID();
}


#if defined(NCBI_OS_LINUX) && defined(PR_SET_NAME)
void CThread::SetCurrentThreadName(const CTempString& name)
{
    prctl(PR_SET_NAME, (unsigned long)name.data(), 0, 0, 0);
}
#else
void CThread::SetCurrentThreadName(const CTempString&)
{
}
#endif


bool CThread::sm_IsExiting = false;
CTimeout CThread::sm_WaitForThreadsTimeout = CTimeout(0.1);


void CThread::SetWaitForAllThreadsTimeout(const CTimeout& timeout)
{
    sm_WaitForThreadsTimeout = timeout;
}


bool CThread::WaitForAllThreads(void)
{
    if (sm_ThreadsCount == 0) return true;
    if ( !IsMain() ) return false;

    CStopWatch sw(CStopWatch::eStart);
    bool infinite = sm_WaitForThreadsTimeout.IsInfinite();
    unsigned long to = 0;
    unsigned long q = 10;
    if ( !infinite ) {
        to = sm_WaitForThreadsTimeout.GetAsMilliSeconds();
        if (to < q) q = to;
    }
    while (sm_ThreadsCount > 0  &&  (infinite || sw.Elapsed()*1000 < to)) {
        SleepMilliSec(q);
    }
    return sm_ThreadsCount == 0;
}


const char* CThreadException::GetErrCodeString(void) const
{
    switch (GetErrCode()) {
    case eRunError:     return "eRunError";
    case eControlError: return "eControlError";
    case eOther:        return "eOther";
    default:            return CException::GetErrCodeString();
    }
}


END_NCBI_SCOPE
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018
0019
0020
0021
0022
0023
0024
0025
0026
0027
0028
0029
0030
0031
0032
0033
0034
0035
0036
0037
0038
0039
0040
0041
0042
0043
0044
0045
0046
0047
0048
0049
0050
0051
0052
0053
0054
0055
0056
0057
0058
0059
0060
0061
0062
0063
0064
0065
0066
0067
0068
0069
0070
0071
0072
0073
0074
0075
0076
0077
0078
0079
0080
0081
0082
0083
0084
0085
0086
0087
0088
0089
0090
0091
0092
0093
0094
0095
0096
0097
0098
0099
0100
0101
0102
0103
0104
0105
0106
0107
0108
0109
0110
0111
0112
0113
0114
0115
0116
0117
0118
0119
0120
0121
0122
0123
0124
0125
0126
0127
0128
0129
0130
0131
0132
0133
0134
0135
0136
0137
0138
0139
0140
0141
0142
0143
0144
0145
0146
0147
0148
0149
0150
0151
0152
0153
0154
0155
0156
0157
0158
0159
0160
0161
0162
0163
0164
0165
0166
0167
0168
0169
0170
0171
0172
0173
0174
0175
0176
0177
0178
0179
0180
0181
0182
0183
0184
0185
0186
0187
0188
0189
0190
0191
0192
0193
0194
0195
0196
0197
0198
0199
0200
0201
0202
0203
0204
0205
0206
0207
0208
0209
0210
0211
0212
0213
0214
0215
0216
0217
0218
0219
0220
0221
0222
0223
0224
0225
0226
0227
0228
0229
0230
0231
0232
0233
0234
0235
0236
0237
0238
0239
0240
0241
0242
0243
0244
0245
0246
0247
0248
0249
0250
0251
0252
0253
0254
0255
0256
0257
0258
0259
0260
0261
0262
0263
0264
0265
0266
0267
0268
0269
0270
0271
0272
0273
0274
0275
0276
0277
0278
0279
0280
0281
0282
0283
0284
0285
0286
0287
0288
0289
0290
0291
0292
0293
0294
0295
0296
0297
0298
0299
0300
0301
0302
0303
0304
0305
0306
0307
0308
0309
0310
0311
0312
0313
0314
0315
0316
0317
0318
0319
0320
0321
0322
0323
0324
0325
0326
0327
0328
0329
0330
0331
0332
0333
0334
0335
0336
0337
0338
0339
0340
0341
0342
0343
0344
0345
0346
0347
0348
0349
0350
0351
0352
0353
0354
0355
0356
0357
0358
0359
0360
0361
0362
0363
0364
0365
0366
0367
0368
0369
0370
0371
0372
0373
0374
0375
0376
0377
0378
0379
0380
0381
0382
0383
0384
0385
0386
0387
0388
0389
0390
0391
0392
0393
0394
0395
0396
0397
0398
0399
0400
0401
0402
0403
0404
0405
0406
0407
0408
0409
0410
0411
0412
0413
0414
0415
0416
0417
0418
0419
0420
0421
0422
0423
0424
0425
0426
0427
0428
0429
0430
0431
0432
0433
0434
0435
0436
0437
0438
0439
0440
0441
0442
0443
0444
0445
0446
0447
0448
0449
0450
0451
0452
0453
0454
0455
0456
0457
0458
0459
0460
0461
0462
0463
0464
0465
0466
0467
0468
0469
0470
0471
0472
0473
0474
0475
0476
0477
0478
0479
0480
0481
0482
0483
0484
0485
0486
0487
0488
0489
0490
0491
0492
0493
0494
0495
0496
0497
0498
0499
0500
0501
0502
0503
0504
0505
0506
0507
0508
0509
0510
0511
0512
0513
0514
0515
0516
0517
0518
0519
0520
0521
0522
0523
0524
0525
0526
0527
0528
0529
0530
0531
0532
0533
0534
0535
0536
0537
0538
0539
0540
0541
0542
0543
0544
0545
0546
0547
0548
0549
0550
0551
0552
0553
0554
0555
0556
0557
0558
0559
0560
0561
0562
0563
0564
0565
0566
0567
0568
0569
0570
0571
0572
0573
0574
0575
0576
0577
0578
0579
0580
0581
0582
0583
0584
0585
0586
0587
0588
0589
0590
0591
0592
0593
0594
0595
0596
0597
0598
0599
0600
0601
0602
0603
0604
0605
0606
0607
0608
0609
0610
0611
0612
0613
0614
0615
0616
0617
0618
0619
0620
0621
0622
0623
0624
0625
0626
0627
0628
0629
0630
0631
0632
0633
0634
0635
0636
0637
0638
0639
0640
0641
0642
0643
0644
0645
0646
0647
0648
0649
0650
0651
0652
0653
0654
0655
0656
0657
0658
0659
0660
0661
0662
0663
0664
0665
0666
0667
0668
0669
0670
0671
0672
0673
0674
0675
0676
0677
0678
0679
0680
0681
0682
0683
0684
0685
0686
0687
0688
0689
0690
0691
0692
0693
0694
0695
0696
0697
0698
0699
0700
0701
0702
0703
0704
0705
0706
0707
0708
0709
0710
0711
0712
0713
0714
0715
0716
0717
0718
0719
0720
0721
0722
0723
0724
0725
0726
0727
0728
0729
0730
0731
0732
0733
0734
0735
0736
0737
0738
0739
0740
0741
0742
0743
0744
0745
0746
0747
0748
0749
0750
0751
0752
0753
0754
0755
0756
0757
0758
0759
0760
0761
0762
0763
0764
0765
0766
0767
0768
0769
0770
0771
0772
0773
0774
0775
0776
0777
0778
0779
0780
0781
0782
0783
0784
0785
0786
0787
0788
0789
0790
0791
0792
0793
0794
0795
0796
0797
0798
0799
0800
0801
0802
0803
0804
0805
0806
0807
0808
0809
0810
0811
0812
0813
0814
0815
0816
0817
0818
0819
0820
0821
0822
0823
0824
0825
0826
0827
0828
0829
0830
0831
0832
0833
0834
0835
0836
0837
0838
0839
0840
0841
0842
0843
0844
0845
0846
0847
0848
0849
0850
0851
0852
0853
0854
0855
0856
0857
0858
0859
0860
0861
0862
0863
0864
0865
0866
0867
0868
0869
0870
0871
0872
0873
0874
0875
0876
0877
0878
0879
0880
0881
0882
0883
0884
0885
0886
0887
0888
0889
0890
0891
0892
0893
0894
0895
0896
0897
0898
0899
0900
0901
0902
0903
0904
0905
0906
0907
0908
0909
0910
0911
0912
0913
0914
0915
0916
0917
0918
0919
0920
0921
0922
0923
0924
0925
0926
0927
0928
0929
0930
0931
0932
0933
0934
0935
0936
0937
0938
0939
0940
0941
0942
0943
0944
0945
0946
0947
0948
0949
0950
0951
0952
0953
0954
0955
0956
0957
0958
0959
0960
0961
0962
0963
0964
0965
0966
0967
0968
0969
0970
0971
0972
0973
0974
0975
0976
0977
0978
0979
0980
0981
0982
0983
0984
0985
0986
0987
0988
0989
0990
0991
0992
0993
0994
0995
0996
0997
0998
0999
1000
1001
1002
1003
1004
1005

-