#include "StdAfx.h"
#if !defined( OSWin_ )
#include <unistd.h>
#endif
#include "threadData.h"
#include <maya/MCommonSystemUtils.h>
 volatile bool threadData::bThreadToExecute =true ;
 volatile bool threadData::bWaitingForCommand =false ;
static threadData tdata ;
struct _threadData *threadData::getThreadData () {
    return (&tdata) ;
}
MThreadRetVal threadData::AsyncModuleThread (void *data) {
    threadData *myData =(threadData *)data ;
    while ( threadData::bThreadToExecute ) {
        int ithreadDataDelay =threadDataDelayDefault ;
        char *val =getenv (threadDataDelayName) ;
        if ( val != NULL && *val != _T('\0') )
            ithreadDataDelay =atoi (val) ;
        MModuleLogic::ModuleDetectionLogicCmdExecute (myData) ;
#if defined(_WIN32) || defined(_WIN64)
        Sleep (ithreadDataDelay * 1000) ;
#else
        sleep (ithreadDataDelay) ;
#endif
    }
    return (0) ;
}
static volatile int g_async_count =0 ;
void threadData::AsyncModuleThreadEnded (void *data) {
    g_async_count++ ;
}
MStatus threadData::startThread () {
 
    
    {
    }
    
    
    
    threadData::bThreadToExecute =true ;
    threadData::bWaitingForCommand =false ;
        return (ms) ;
        threadData::AsyncModuleThread,
        (void *)threadData::getThreadData (),
        threadData::AsyncModuleThreadEnded,
        NULL
    ) ;
    return (ms) ;
}
bool threadData::Maya_InterlockedCompare (volatile int *variable, int compareValue) {
    exchangeSpinLock.
lock () ;
    bool rtn =(*variable == compareValue) ;
    exchangeSpinLock.unlock () ;
    return (rtn) ;
}
void threadData::WaitForAsyncThreads (int val) {
    while ( !threadData::Maya_InterlockedCompare (&g_async_count, val)) {
#if defined(_WIN32) || defined(_WIN64)
        Sleep (0) ;
#else
        sleep (0) ;
#endif
    }
}
void threadData::stopThread () {
    
    threadData::bThreadToExecute =false ;
    
    threadData::WaitForAsyncThreads (1) ;
}