char* fnMy_MkTemp(char* templatestr) { char* pXs=NULL; char numbuf[50]={'\0'}; int count=0; char* pPid=NULL; char termchar = '\0'; char letter = 'a'; char letter1 = 'a'; if (templatestr && (pXs = strstr(templatestr, (char *)"XXXXXX"))) { // generate temp name termchar = pXs[6]; ltoa(GetThreadID(), numbuf, 16); // numbuf[sizeof(numbuf)-1] = '\0'; numbuf[strlen(numbuf)-1] = '\0'; // beware! thread IDs are 8 hex digits on NW 4.11 and only the // lower digits seem to change, whereas on NW 5 they are in the // range of < 1000 hex or 3 hex digits in length. So the following // logic ensures we use the least significant portion of the number. if (strlen(numbuf) > 5) pPid = &numbuf[strlen(numbuf)-5]; else pPid = numbuf; /** Backtick operation uses temp files that are stored under NWDEFPERLTEMP directory. They are temporarily used and then cleaned up after usage. In cases where multiple backtick operations are used that call some complex scripts, new temp files will be created before the old ones are deleted. So, we need to have a provision to create many temp files. Hence the below logic. It is found that provision for 26 files may not be enough in some cases. This below logic allows 26 files (like, pla00015.tmp through plz00015.tmp) plus 6x26=676 (like, plaa0015.tmp through plzz0015.tmp) **/ letter = 'a'; do { sprintf(pXs, (char *)"%c%05.5s", letter, pPid); pXs[6] = termchar; if (access(templatestr, 0) != 0) // File does not exist { return templatestr; } letter++; } while (letter <= 'z'); letter1 = 'a'; do { letter = 'a'; do { sprintf(pXs, (char *)"%c%c%04.5s", letter1, letter, pPid); pXs[6] = termchar; if (access(templatestr, 0) != 0) // File does not exist { return templatestr; } letter++; } while (letter <= 'z'); letter1++; } while (letter1 <= 'z'); errno = ENOENT; return NULL; } else { errno = EINVAL; return NULL; } }
int LoadConfigEngine::StopThread(void) { void *pReturnValue = 0; return pthread_join(GetThreadID(), &pReturnValue); }
void SenatorRun() { int cashDollars; int clerkStatus; int index; int tid; tid = GetThreadID(); Acquire(customerSenatorUIDLock); index = customerSenatorUID++; Release(customerSenatorUIDLock); tprintf("Senator[%d]: Acquiring customerOfficeLock\n", index,0,0,"",""); /*customerOfficeLock->Acquire();*/ Acquire(entryLock); if (customersInOffice > 0){ tprintf("Senator[%d]: There are other Customers in office, going to Senator waiting room\n", index,0,0,"",""); senatorsInWaitingRoom++; tprintf("Senator[%d]: In the waiting room, taking a nap...\n", index,0,0,"",""); /*senatorWaitingRoomCV->Wait(senatorWaitingRoomLock);*/ Wait(senatorWaitingRoomCV, entryLock); tprintf("Senator[%d]: Waking up, going to the passport office!\n", index,0,0,"",""); senatorsInWaitingRoom--; } tprintf("Senator [%d]: Entering the passport office...\n",index,0,0,"",""); /*senator start up code*/ cashDollars = ((Rand() % 4) * 500) + 100; printf("Senator [%d] has money = [$%d] ... tid = %d\n",index,cashDollars,tid,"",""); senatorsInOffice++; Release(entryLock); /*choose line*/ tprintf("Senator [%d]: Deciding between AppClerk and PictureClerk...\n", index,0,0,"",""); if(cashDollars > 100) /*find priveledged line with shortest length*/ { /*appPicLineLock->Acquire();*/ Acquire(appPicLineLock); printf("Senator [%d] finds the minimum [priveledged] queue for [ApplicationClerk/PictureClerk]\n", index,0,0,"",""); if(privAppLineLength<=privPicLineLength) { /*appPicLineLock->Release();*/ Release(appPicLineLock); printf("Senator [%d] goes to [ApplicationClerk] first.\n",index,0,0,"",""); doAppClerk(&index, &cashDollars); doPicClerk(&index, &cashDollars); } else { /*appPicLineLock->Release();*/ Release(appPicLineLock); printf("Senator [%d] goes to [PictureClerk] first.\n",index,0,0,"",""); doPicClerk(&index, &cashDollars); doAppClerk(&index, &cashDollars); } } else/*find regular line with shortest length*/ { /*appPicLineLock->Acquire();*/ Acquire(appPicLineLock); printf("Senator [%d] finds the minimum [regular] queue for [ApplicationClerk/PictureClerk]\n", index,0,0,"",""); if(regAppLineLength<=regPicLineLength) { /*appPicLineLock->Release();*/ Release(appPicLineLock); printf("Senator [%d] goes to [ApplicationClerk].\n",index,0,0,"",""); doAppClerk(&index, &cashDollars); doPicClerk(&index, &cashDollars); } else { /*appPicLineLock->Release();*/ Release(appPicLineLock); printf("Senator [%d] goes to [PictureClerk].\n",index,0,0,"",""); doPicClerk(&index, &cashDollars); doAppClerk(&index, &cashDollars); } } /*hit up the passport clerk*/ doPassPortClerk(&index, &cashDollars); /*proceed to cashier*/ doCashierClerk(&index, &cashDollars); Exit(0); }
std::string ThreadIDString(void) const { return Poco::format("[%d] ", GetThreadID()); }
ThreadContext* fnAddThreadCtx(long lTLSIndex, void *t) { ThreadContext* tip = NULL; ThreadContext* temp = NULL; if (g_tCtxSem) { #ifdef MPK_ON kSemaphoreWait(g_tCtxSem); #else WaitOnLocalSemaphore(g_tCtxSem); #endif //MPK_ON } // add a new one to the beginning of the list // tip = (ThreadContext *) malloc(sizeof(ThreadContext)); if (tip == NULL) { if (g_tCtxSem) { #ifdef MPK_ON kSemaphoreSignal(g_tCtxSem); #else SignalLocalSemaphore(g_tCtxSem); #endif //MPK_ON } return NULL; } #ifdef MPK_ON lTLSIndex = labs(kCurrentThread()); #else lTLSIndex = GetThreadID(); #endif //MPK_ON tip->next = NULL; tip->tid = lTLSIndex; tip->tInfo = t; if(g_ThreadCtx==NULL) { g_ThreadCtx = tip; } else { int count=0; //Traverse to the end temp = g_ThreadCtx; while(temp->next != NULL) { temp = temp->next; count++; } temp->next = tip; } if (g_tCtxSem) { #ifdef MPK_ON kSemaphoreSignal(g_tCtxSem); #else SignalLocalSemaphore(g_tCtxSem); #endif //MPK_ON } return tip; }
void __InitMultipleThread( void ) /*******************************/ { if( __GetThreadPtr != __MultipleThread ) { #if defined( _NETWARE_CLIB ) { /* __ThreadData[ 0 ] is used whenever GetThreadID() returns a pointer not in our __ThreadIDs list - ie. whenever it returns NULL, a pointer to a thread we didn't create, or an invalid pointer */ void *ptr; ptr = lib_calloc( 1, __ThreadDataSize ); if( ptr == NULL ) { __fatal_runtime_error( "Unable to allocate thread-specific data", 1 ); } __ThreadData[ 0 ].data = ptr; __ThreadData[ 0 ].allocated_entry = 1; __ThreadData[ 0 ].data->__allocated = 1; __ThreadData[ 0 ].data->__randnext = 1; __ThreadData[ 0 ].data->__data_size = __ThreadDataSize; if( __initthread( ptr ) ) { lib_free( ptr ); __fatal_runtime_error( "Unable to initialize thread-specific data", 1 ); } ptr = lib_calloc( 1, __ThreadDataSize ); if( ptr == NULL ) { __fatal_runtime_error( "Unable to allocate thread-specific data", 1 ); } __FirstThreadData = ptr; __FirstThreadData->__allocated = 1; __FirstThreadData->__randnext = 1; __FirstThreadData->__data_size = __ThreadDataSize; __ThreadData[ 1 ].data = __FirstThreadData; __ThreadData[ 1 ].allocated_entry = __FirstThreadData->__allocated; __ThreadIDs[ 1 ] = GetThreadID(); if( __initthread( ptr ) ) { lib_free( ptr ); __fatal_runtime_error( "Unable to initialize thread-specific data", 1 ); } } #elif defined( _NETWARE_LIBC ) InitSemaphore.semaphore = 0; /* sema4 is mutex in this case */ InitSemaphore.initialized = 1; //_ThreadExitRtn = &__ThreadExit; - might need this at some point?? // Note: __AddThreadData uses the InitSemaphore, _AccessTDList & _ReleaseTDList __FirstThreadData->thread_id = GetCurrentThreadId(); __AddThreadData( __FirstThreadData->thread_id, __FirstThreadData ); if(0 != NXKeySetValue(__NXSlotID, __FirstThreadData)) { __fatal_runtime_error( "Unable to initialize thread-specific data", 1 ); } #elif defined( __NT__ ) InitSemaphore.semaphore = __NTGetCriticalSection(); InitSemaphore.initialized = 1; _ThreadExitRtn = &__ThreadExit; // Note: __AddThreadData uses the InitSemaphore, _AccessTDList & _ReleaseTDList __AddThreadData( __FirstThreadData->thread_id, __FirstThreadData ); TlsSetValue( __TlsIndex, __FirstThreadData ); #elif defined( __QNX__ ) __qsem_init( &InitSemaphore.semaphore, 1, 1 ); InitSemaphore.initialized = 1; // first thread data already in magic memory #elif defined( __LINUX__ ) // TODO: Init semaphores for Linux #elif defined( __RDOS__ ) InitSemaphore.semaphore = RdosCreateSection(); InitSemaphore.initialized = 1; __AddThreadData( __FirstThreadData->thread_id, __FirstThreadData ); __tls_set_value( __TlsIndex, __FirstThreadData ); #elif defined( __RDOSDEV__ ) RdosInitKernelSection( &InitSemaphore.semaphore ); InitSemaphore.initialized = 1; #elif defined( __OS2__ ) DosCreateMutexSem( NULL, &InitSemaphore.semaphore, 0, FALSE ); InitSemaphore.initialized = 1; __ThreadData[1].data = __FirstThreadData; __ThreadData[1].allocated_entry = __FirstThreadData->__allocated; #else #error Multiple thread support is not defined for this platform #endif #if !defined( _M_I86 ) // Set these up after we have created the InitSemaphore #if !defined (_THIN_LIB) _AccessFileH = &__AccessFileH; _ReleaseFileH = &__ReleaseFileH; _AccessIOB = &__AccessIOB; _ReleaseIOB = &__ReleaseIOB; #endif _AccessTDList = &__AccessTDList; _ReleaseTDList = &__ReleaseTDList; __AccessSema4 = &__AccessSemaphore; __ReleaseSema4 = &__ReleaseSemaphore; __CloseSema4 = &__CloseSemaphore; #if !defined( __NETWARE__ ) _AccessNHeap = &__AccessNHeap; _AccessFHeap = &__AccessFHeap; _ReleaseNHeap = &__ReleaseNHeap; _ReleaseFHeap = &__ReleaseFHeap; #endif #if defined( __NT__ ) _AccessFList = &__AccessFList; _ReleaseFList = &__ReleaseFList; #endif #endif __GetThreadPtr = __MultipleThread; } }
VOID CLogFile::DiskLog(enum_LOG_LEVEL logLevel, const CHAR* pLogString , ...) { //等级太低,不需打印控制台和文件 if (logLevel < m_eConsoleLogLevel && logLevel < m_eFileLogLevel) { return ; } CHAR szLine[MAX_LOG_LINE] = {0}; va_list va; va_start(va,pLogString); #ifdef __LINUX vsprintf(szLine,pLogString,va); #else vsprintf_s(szLine,MAX_LOG_LINE,pLogString,va); #endif va_end(va); DateTime now; CHAR szLogStr[MAX_LOG_LINE] = {'\0'}; _snprintf(szLogStr, MAX_LOG_LINE, "%2d/%02d/%02d %02d:%02d:%02d.%03d tId:%ld %s\n", now.GetYear(), now.GetMonth(), now.GetDay(), now.GetHour(), now.GetMinute(), now.GetSecond(), now.GetMilliSecond(), GetThreadID(), szLine); //高等与控制台等级,则打印到控制台 if (logLevel >= m_eConsoleLogLevel) { printf("%s", szLogStr); } //高等与文件等级,则打印到文件 if (logLevel >= m_eFileLogLevel) { CSmartLock sLock(m_lock); INT nLogStrLen = strlen(szLogStr); if ((m_bBackBufAvailable) && (m_pWriteBuf + nLogStrLen - m_pFrontBuf >= LOG_BUF_LEN)) { //如果back有东西, front还写不下,就要写2次文件了,不过这种情况应该很少 WriteBackBufToFile(); } if (m_pWriteBuf + nLogStrLen - m_pFrontBuf >= LOG_BUF_LEN) { //front写不下,那么back肯定空着 SwitchBuf(); } //写入front strcpy( m_pWriteBuf, szLogStr ); m_pWriteBuf += nLogStrLen; //全写入文件中 WriteAllBufToFile(); } }
bool CMyTaskThread::IsSelfThread() { return GetCurrentThreadId()==GetThreadID(); }
static PSERVICE_ROUTE _LoadService( CTEXTSTR service , EventHandlerFunction EventHandler , EventHandlerFunctionEx EventHandlerEx , EventHandlerFunctionExx EventHandlerExx , server_message_handler handler , server_message_handler_ex handler_ex , uintptr_t psv ) { MSGIDTYPE MsgID; MsgSrv_ReplyServiceLoad msg; size_t MsgLen = sizeof( msg ); // expect MsgBase = 0, EventMessgaeCount = 1 PEVENTHANDLER pHandler; // can check now if some other part of this has loaded // this service. // reset this status... if( !_InitMessageService( service?FALSE:TRUE ) ) { #ifdef DEBUG_MSGQ_OPEN lprintf( WIDE("Load of %s message service failed."), service ); #endif return NULL; } if( service ) { RegisterWithMasterService(); if( !g.flags.bAliveThreadStarted ) { // this timer monitors ALL clients for inactivity // it will probe them with RU_ALIVE messages // to which they must respond otherwise be termintated. g.flags.bAliveThreadStarted = 1; AddTimer( CLIENT_TIMEOUT/4, MonitorClientActive, 0 ); // each service gets 1 thread to handle their own // messages... services do not have 'events' generated // to them. } #if 0 // always query for service, don't short cut... ? while( pHandler ) { // only one connection to any given service name // may be maintained. The service itself is resulted... if( !strcmp( pHandler->servicename, service ) ) return &pHandler->RouteID; pHandler = pHandler->next; } #endif EnterCriticalSec( &g.csLoading ); pHandler = New( EVENTHANDLER ); MemSet( pHandler, 0, sizeof( EVENTHANDLER ) ); //InitializeCriticalSec( &pHandler->csMsgTransact ); pHandler->servicename = StrDup( service ); pHandler->RouteID.dest.process_id = 1; pHandler->RouteID.dest.service_id = 0; pHandler->RouteID.source.process_id = g.my_message_id; pHandler->RouteID.source.service_id = 0; //lprintf( WIDE("Allocating local structure which manages our connection to this service...") ); // MsgInfo is used both on the send and receives the // responce from the service... // LoadService goes to the msgsvr and requests the // location of the service. if( !TransactRoutedServerMultiMessageEx( &pHandler->RouteID , MSG_ServiceLoad, 1 , &MsgID, &msg, &MsgLen , 250 /* short timeout */ , service, (StrLen( service ) + 1) *sizeof(TEXTCHAR) // include NUL ) ) { Log( WIDE("Transact message timeout.") ); Release( pHandler ); LeaveCriticalSec( &g.csLoading ); return NULL; } if( MsgID != (MSG_ServiceLoad|SERVER_SUCCESS) ) { lprintf( WIDE("Server reports it failed to load [%s] (%08") _MsgID_f WIDE("!=%08" ) _MsgID_f WIDE(")") , service , MsgID , (MSGIDTYPE)(MSG_ServiceLoad|SERVER_SUCCESS) ); Release( pHandler ); LeaveCriticalSec( &g.csLoading ); return NULL; } // uncorrectable anymore. //if( MsgLen == 16 ) //{ // lprintf( WIDE("Old server load service responce... lacks the PID of the event handler.") ); //} if( MsgLen != sizeof( msg ) ) { lprintf( WIDE("Server responce was the wrong length!!! %") _size_f WIDE(" expecting %")_size_f, MsgLen, sizeof( msg ) ); Release( pHandler ); LeaveCriticalSec( &g.csLoading ); return NULL; } } else { // loading special NULL service. // the NULL service looks like a queue available // for events only? fakes a server response in msg. pHandler = New( EVENTHANDLER ); MemSet( pHandler, 0, sizeof( EVENTHANDLER ) ); //InitializeCriticalSec( &pHandler->csMsgTransact ); pHandler->RouteID.dest.process_id = g.my_message_id; pHandler->RouteID.dest.service_id = 0; pHandler->servicename = StrDup( WIDE("local_events") ); msg.ServiceID = 0; // this is a special event channel to myself. //lprintf( WIDE("opening local only service... we're making up numbers here.") ); if( g.pLocalEventThread ) { msg.thread = GetThreadID( g.pLocalEventThread ); } else { lprintf( WIDE("Event message system has not started correctly...") ); Release( pHandler ); LeaveCriticalSec( &g.csLoading ); return NULL; } } // EVENTHANDLER is the outbound structure to idenfity // the service information which messages go where... { //pHandler = Allocate( sizeof( EVENTHANDLER ) + strlen( service?service:"local_events" ) ); //strcpy( pHandler->servicename, service?service:"local_events" ); //lprintf( WIDE("Allocating local structure which manages our connection to this service...") ); pHandler->flags.destroyed = 0; pHandler->flags.dispatched = 0; //pHandler->MsgCountEvents = msg.events; //pHandler->MsgCount = msg.functions; pHandler->Handler = EventHandler; pHandler->HandlerEx = EventHandlerEx; pHandler->HandlerExx = EventHandlerExx; pHandler->psv = psv; // thread ID to wake for events? or to probe? // thread ID unused. pHandler->EventID = msg.thread; if( service ) { pHandler->flags.local_service = 0; //pHandler->RouteID.dest = msg.ServiceID; // magic place where source ID is.. pHandler->msgq_events = g.msgq_event; } else { pHandler->flags.local_service = 1; pHandler->RouteID.dest.process_id = g.my_message_id; pHandler->RouteID.dest.service_id = 0; pHandler->msgq_events = g.msgq_local; } LinkThing( g.pHandlers, pHandler ); if( service ) { PSERVICE_CLIENT pClient = AddClient( &pHandler->RouteID ); // hang this on the list of services to check... pClient->flags.is_service = 1; pClient->handler = pHandler; } LeaveCriticalSec( &g.csLoading ); } return &pHandler->RouteID; }
BOOL CWin32Thread::IsInThread()const { return GetCurrentThreadId()==GetThreadID(); }
BOOL CDOSObjectProxyService::OnStart() { FUNCTION_BEGIN; m_ThreadPerformanceCounter.Init(GetThreadHandle(),THREAD_CPU_COUNT_TIME); if(!m_ConnectionPool.Create(((CDOSServer *)GetServer())->GetConfig().MaxProxyConnection)) { PrintDOSLog(0xff0000,_T("创建%u大小的连接池失败!"), ((CDOSServer *)GetServer())->GetConfig().MaxProxyConnection); return FALSE; } if(!m_MsgQueue.Create(((CDOSServer *)GetServer())->GetConfig().MaxProxyMsgQueue)) { PrintDOSLog(0xff0000,_T("创建%u大小的消息队列失败!"), ((CDOSServer *)GetServer())->GetConfig().MaxProxyMsgQueue); return FALSE; } if(!m_MessageMap.Create(((CDOSServer *)GetServer())->GetConfig().MaxProxyGlobalMsgMap)) { PrintDOSLog(0xff0000,_T("创建%u大小的消息映射表失败!"), ((CDOSServer *)GetServer())->GetConfig().MaxProxyGlobalMsgMap); return FALSE; } if(((CDOSServer *)GetServer())->GetConfig().ProxyMsgMinCompressSize) { if (lzo_init() != LZO_E_OK) { PrintDOSLog(0xff0000,_T("代理服务开启消息压缩失败")); return FALSE; } PrintDOSDebugLog(0xff0000,_T("代理服务开启消息压缩")); } if(!Create(IPPROTO_TCP, DEFAULT_SERVER_ACCEPT_QUEUE, DEFAULT_SERVER_RECV_DATA_QUEUE, ((CDOSServer *)GetServer())->GetConfig().ProxySendBufferSize, DEFAULT_PARALLEL_ACCEPT, DEFAULT_PARALLEL_RECV, false)) { PrintDOSLog(0xffff,_T("代理服务创建失败!")); return FALSE; } if(!StartListen(((CDOSServer *)GetServer())->GetConfig().ObjectProxyServiceListenAddress)) { PrintDOSLog(0xffff,_T("代理服务侦听于(%s:%u)失败!"), ((CDOSServer *)GetServer())->GetConfig().ObjectProxyServiceListenAddress.GetIPString(), ((CDOSServer *)GetServer())->GetConfig().ObjectProxyServiceListenAddress.GetPort()); return FALSE; } PrintDOSLog(0xffff,_T("代理服务侦听于(%s:%u)!"), ((CDOSServer *)GetServer())->GetConfig().ObjectProxyServiceListenAddress.GetIPString(), ((CDOSServer *)GetServer())->GetConfig().ObjectProxyServiceListenAddress.GetPort()); PrintDOSLog(0xff0000,_T("对象代理线程[%u]已启动"),GetThreadID()); return TRUE; FUNCTION_END; return FALSE; }