unsigned int __stdcall Thread_RecvMsg(void *data) { //int nNetTimeout = 30000; //setsockopt(sockClient,SOL_SOCKET,SO_RCVTIMEO,(char*)&nNetTimeout,sizeof(int)); while(1) { int nRet = recv(sockClient,(char*)recvBuf,RECV_BUF_LEN,0); if((nRet == SOCKET_ERROR)|| (nRet == 0)) { trySetConnectSocket(true); critical_section.Lock(); if(exit_flag) { critical_section.Unlock(); //shutdown(sockClient,SD_RECEIVE); shutdown(sockClient,SD_BOTH); closesocket(sockClient); return -1; } critical_section.Unlock(); Sleep(2000); } } }
INT_PTR NewGUI_DoModal(CDialog* pDlg) { if(pDlg == NULL) { ASSERT(FALSE); return IDCANCEL; } CPwSafeDlg* pRootDlg = (CPwSafeDlg*)KPMI_GetMainDialog(); ASSERT(pRootDlg != NULL); VERIFY(g_csDoModalRoot.Lock() != FALSE); if(pRootDlg != NULL) { pRootDlg->NotifyUserActivity(); pRootDlg->_SetDisplayDialog(true); } VERIFY(CGlobalWindowManager::AddDialog(pDlg) == S_OK); VERIFY(g_csDoModalRoot.Unlock() != FALSE); const INT_PTR r = pDlg->DoModal(); VERIFY(g_csDoModalRoot.Lock() != FALSE); VERIFY(CGlobalWindowManager::RemoveDialog(pDlg) == S_OK); if(pRootDlg != NULL) { pRootDlg->NotifyUserActivity(); pRootDlg->_SetDisplayDialog(false); } VERIFY(g_csDoModalRoot.Unlock() != FALSE); return r; }
//unsigned int __stdcall Thread_ReconnectSocket(void *data) unsigned int __stdcall Thread_ReconnectSocket(LPVOID lpParam) { ThreadProcInfo* pInfo = (ThreadProcInfo*) lpParam; while(1) { WaitForSingleObject(g_readyEvent_ConnectSocket, INFINITE); WaitForSingleObject(socketMutex,INFINITE); critical_section.Lock(); if(exit_flag) { //shutdown(sockClient,SD_BOTH); //closesocket(sockClient); critical_section.Unlock(); ResetEvent(g_readyEvent_ConnectSocket); ReleaseMutex(socketMutex); return -1; } critical_section.Unlock(); while(SOCKET_ERROR == connect(sockClient,(struct sockaddr *)&serverAddr,sizeof(serverAddr))) { critical_section.Lock(); if(exit_flag) { //shutdown(sockClient,SD_BOTH); //closesocket(sockClient); critical_section.Unlock(); ResetEvent(g_readyEvent_ConnectSocket); ReleaseMutex(socketMutex); return -1; } critical_section.Unlock(); int errorCode = WSAGetLastError(); if(errorCode == 10056 || errorCode == 10038) { closesocket(sockClient); while(INVALID_SOCKET == socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) { //printf("COMM: Creating socket failed!\n"); PostMessage(pInfo->hWnd,WM_DISPLAYSTATUS,NULL,STATUS_CREATE_SOCKET_FAIL); Sleep(1000); } } //printf("COMM: Connect socket failed!\n"); PostMessage(pInfo->hWnd,WM_DISPLAYSTATUS,NULL,STATUS_CONNECT_SOCKET_FAIL); Sleep(2000); } PostMessage(pInfo->hWnd,WM_DISPLAYSTATUS,NULL,STATUS_CONNECT_SOCKET_SUCCESS); ResetEvent(g_readyEvent_ConnectSocket); ReleaseMutex(socketMutex); } }
void CDummyWnd::ProcessMessageServer(CMessage *pMsg) { COMMON_PACKET cmnpck; pMsg->GetData(&cmnpck, 0, sizeof(cmnpck)); switch(cmnpck.header) // ÆÐŶ Çì´õ °Ë»ö { case GSM_SERVERINFO : // °ÔÀÓ ¼¹ö Á¤º¸ÀÏ °æ¿ì { //AfxMessageBox("°ÔÀÓ ¼¹ö Á¤º¸ ÀúÀå."); SERVERINFO si; CHANNELINFO ci; int nLen = pMsg->GetData(&si, 0, sizeof(si)); // ¿ì¼± °ÔÀÓ ¼¹ö ÀÚüÀÇ Á¤º¸¸¦ ¾òÀ½ LPSERVER server = m_ServerManager.GetServer((SOCKET)pMsg->GetSocket()); // ÆÐŶÀ» º¸³½ ¼¹ö¸¦ ãÀ½ if(server != NULL) // Á¤»óÀûÀÎ ¼¹ö Æ÷ÀÎÅ͸¦ °¡Á®¿ÔÀ» °æ¿ì { server->id = si.id; // ¼¹öÀÇ ¾ÆÀ̵ð ÀúÀå server->ip = (char *)si.ip; // ¾ÆÀÌÇÇ ÀúÀå server->portno = si.port; // Æ÷Æ®¹øÈ£ ÀúÀå server->maxchannel = si.channels; server->rooms = si.rooms; if(!server->channel.size()) // ÃÖÃÊ¿¡ Á¢¼ÓÇÑ ¼¹öÀÏ °æ¿ì ä³ÎÁ¤º¸°¡ ¾øÀ½ { CHANNEL channel; for(int i = 0 ; i < si.channels ; i++) // Àüü ä³Î°¹¼ö¸¸Å { nLen += pMsg->GetData(&ci, nLen, sizeof(ci)); // ä³Î Á¤º¸¸¦ Çϳª¾¿ Àоî¿È channel = ci; // ä³ÎÁ¤º¸¸¦ Çϳª¾¿ ÀúÀå server->channel.push_back(channel); // ä³ÎÀ» ¸®½ºÆ®¿¡ Ãß°¡ } } else // ÀÌ¹Ì Ã¤³Î Á¤º¸°¡ Á¸ÀçÇÒ °æ¿ì // ÁÖ±âÀûÀÎ ¼¹ö Á¤º¸ÀÇ ¿äûÀÏ °æ¿ì { g_Critical.Lock(); list<CHANNEL>::iterator i = server->channel.begin(); for(; i != server->channel.end() ; i++) { LPCHANNEL lpchannel = &(*i); nLen += pMsg->GetData(&ci, nLen, sizeof(ci)); *lpchannel = ci; } g_Critical.Unlock(); } } } break; } }
//插入1条任务结果 bool CSmartCommunicationDlg::SMT_InsertOneTaskResult(SMARTTASKRESULT mTaskResult) { g_CriticalSectionLock.Lock(); g_LSaveTaskResult.push_back(mTaskResult); g_CriticalSectionLock.Unlock(); return true; }
//Thread safe way to update the load log void CLoadLTADlg::UpdateLoadLog() { CString sTextToAdd; g_LoadLogPipeCS.Lock(INFINITE); sTextToAdd = sm_sLoadLogPipe; sm_sLoadLogPipe = ""; g_LoadLogPipeCS.Unlock(); if(!sTextToAdd.IsEmpty()) { CString sLogText; CEdit* pEdit = ((CEdit*)GetDlgItem(IDC_LOADLOG)); pEdit->GetWindowText(sLogText); sLogText += sTextToAdd; pEdit->SetWindowText(sLogText); pEdit->LineScroll(pEdit->GetLineCount()); } }
long long EHS::StaticGetTotalBytesSent ( void ) { ms_StatsCS.Lock(); long long llResult = ms_HttpTotalBytesSent; ms_StatsCS.Unlock(); return llResult; }
void StatsNumResponsesInc( void ) { ms_StatsCS.Lock(); ms_AllocationStats.uiTotalNumResponses++; ms_AllocationStats.uiActiveNumResponses++; ms_StatsCS.Unlock(); }
void StatsBytesAllocated( int nBodyLength ) { ms_StatsCS.Lock(); ms_AllocationStats.uiTotalKBAllocated += nBodyLength / 1024; ms_AllocationStats.uiActiveKBAllocated += nBodyLength / 1024; ms_StatsCS.Unlock(); }
// // Retrieves the number of milliseconds that have elapsed since some arbitrary point in time. // // GetTickCount64() exists on Vista and up and is like GetTickCount() except it returns // an __int64 and will effectively never wrap. This is an emulated version for XP and down. // Note: Wrap around issue is only defeated if the gap between calls is less than 24 days. // long long SharedUtil::GetTickCount64_ ( void ) { ms_criticalSection.Lock (); static long long llCurrent = ( GetTickCountInternal () % 300000 + 200000 ); static uint uiWas = GetTickCountInternal(); uint uiNow = GetTickCountInternal(); uint uiDelta = uiNow - uiWas; uiWas = uiNow; // Ensure delta is not negative if ( uiDelta > 0x80000000 ) uiDelta = 0; // Or greater than 600 seconds if ( uiDelta > 600 * 1000 ) uiDelta = 600 * 1000; // Add delta to accumulator llCurrent += uiDelta; // Add debug value llCurrent += ms_llTickCountAdd; ms_llTickCountAdd = 0; long long llResult = llCurrent; ms_criticalSection.Unlock (); return llResult; }
void LogManager::AddErrorMessenger(Logger::ErrorMessenger* messenger) { m_CritSection.Lock(); S3D_ASSERT(messenger); m_errorMessengers.push_back(messenger); m_CritSection.Unlock(); }
//Thread safe way to clear the load log void CLoadLTADlg::ClearLoadLog() { g_LoadLogPipeCS.Lock(INFINITE); sm_sLoadLogPipe = ""; g_LoadLogPipeCS.Unlock(); }
//Thread safe way to set if the loading thread is done void CLoadLTADlg::SetLoadThreadDone(BOOL bDone) { g_ThreadDoneCS.Lock(INFINITE); sm_bLoadThreadDone = bDone; g_ThreadDoneCS.Unlock(); }
//Thread safe way to add text onto the end of the load log void CLoadLTADlg::AppendLoadLog(const char* pszString) { g_LoadLogPipeCS.Lock(INFINITE); sm_sLoadLogPipe += pszString; g_LoadLogPipeCS.Unlock(); }
void CDlgObjectManager::OnObjmngDelete() { if(!m_hI) return; CCriticalSection cs; cs.Lock(); CMyObject* pObj; for( int i=0; i<m_pObPtrArray->GetSize(); i++) { pObj = m_pObPtrArray->GetAt(i); if( m_tree.GetItemText(m_hI) == pObj->GetIdName() ) { int res = AfxMessageBox("Delete? Sure?", MB_YESNO | MB_ICONQUESTION); if( res == IDYES ) { m_pObPtrArray->RemoveAt( i ); m_tree.DeleteItem(m_hI); m_hI = NULL; cs.Unlock(); m_pDoc->SetModifiedFlag(); if( pObj->IsKindOf(RUNTIME_CLASS( CImgReferenced )) ) m_pDoc->UpdateAllViews(NULL, UPDATE_BITMAP_DELETE); else if( pObj->IsKindOf(RUNTIME_CLASS(CGridObj)) ) m_pDoc->UpdateAllViews(NULL, UPDATE_LEADHRZ_DELETE); else if( pObj->IsKindOf(RUNTIME_CLASS(CData3D)) ) m_pDoc->UpdateAllViews(NULL, UPDATE_DATA3D_DELETE); else m_pDoc->UpdateAllViews(NULL); delete pObj; return; } } } CBody* pBd; pBd = (CBody*) FindBody(m_hI); if(pBd) { int res = AfxMessageBox("Delete Body? Sure?", MB_YESNO | MB_ICONQUESTION); if( res == IDYES ) { m_pDoc->GetModel()->DeleteBody( pBd->GetID() ); m_tree.DeleteItem(m_hI); m_hI = NULL; m_pDoc->SetModifiedFlag(); m_pDoc->UpdateAllViews(NULL, UPDATE_BODY_EDIT_DELETE); } } cs.Unlock(); }
int WINAPI FindDupes(const char* szList, HWND hParent) { AFX_MANAGE_STATE(AfxGetAppModuleState()); hStopEvent=CreateEvent(0,0,0,0); sListOfImages.RemoveAll(); sListOfImagesToDelete.RemoveAll(); sListOfImageDibs.RemoveAll(); CString sFiles=szList; sFiles.Replace("\r",""); sFiles+="\n"; while(sFiles.GetLength()>0){ CString sWPTitle=sFiles.SpanExcluding("\n"); if(strlen(sWPTitle)!=strlen(sFiles)){ sFiles=sFiles.Mid(strlen(sWPTitle)+1); }else{ sFiles=""; } if(sWPTitle!="" && FindMini(sFiles,sWPTitle+"\n")==-1){ sListOfImages.Add(sWPTitle); } } if(hCheckThread){ TerminateThread(hCheckThread,0); hCheckThread=0; } DWORD dwID=0; hCheckThread=CreateThread(0,0,CheckImages,0,0,&dwID); DialogBox(theApp.m_hInstance,MAKEINTRESOURCE(IDD_DIALOG),hParent,OptionsDialogProc); bStopCheck=1; csCheck.Lock(); csCheck.Unlock(); WaitForSingleObject(hStopEvent,1000); CloseHandle(hStopEvent); if(hCheckThread){ TerminateThread(hCheckThread,0); } CloseHandle(hCheckThread); hCheckThread=0; hStopEvent=0; for(int i=0;i<sListOfImageDibs.GetSize();i++){ if(sListOfImageDibs[i]){ delete sListOfImageDibs[i]; } } sPathInLeft=""; sPathInRight=""; if(btLeft){ _bmpX()->ReleaseBmp(btLeft); btLeft=0; } if(btRight){ _bmpX()->ReleaseBmp(btRight); btRight=0; } return lDeletedFiles; }
BOOL CalculateExpression_Ole(CString& sExpr, CString sLang, BOOL bInSilence, int iEntryPoint) { cs.Lock(); int iRes=0; ::CoInitialize(NULL); BOOL bJScriptLang=(sLang=="JScript" || sLang==""); BOOL bVBScriptLang=(sLang=="VBScript"); if(bJScriptLang || bVBScriptLang) {// Создаем область видимости чтобы разрушение ком-объекта было нормальным MSScriptControl::IScriptControlPtr ScriptEngine; ScriptEngine.CreateInstance("MSScriptControl.ScriptControl"); if(bJScriptLang){ ScriptEngine->Language="JScript"; }else if(bVBScriptLang){ ScriptEngine->Language="VBScript"; }else{ ScriptEngine->Language=(const char*)sLang; } ScriptEngine->Timeout = -1;//No timeout try {//RET_FAIL(spAS->AddNamedItem(OLESTR("MyObject"), SCRIPTITEM_ISVISIBLE | SCRIPTITEM_ISSOURCE), "IActiveScript::AddNamedItem()"); _variant_t result; if(!bJScriptLang){ sExpr=CString("Dim OUTPUT\r\n")+sExpr; ScriptEngine->ExecuteStatement(bstr_t(sExpr)); sExpr="OUTPUT"; result=ScriptEngine->Eval(bstr_t(sExpr)); }else{ result=ScriptEngine->Eval(bstr_t(sExpr)); } sExpr=(const char*)_bstr_t(result); iRes=1; }catch(_com_error err){ if(!bInSilence){ //FLOG1("Script error: \n%s\n",sExpr) CString sErr((BSTR)err.Description()); CString sErrSource((BSTR)err.Source()); if(sErrSource!=""){ sErr+="\n"; sErr+=sErrSource; } if(sErr==""){ sErr=GetCOMError(err.Error()); } AfxMessageBox(sErr); } iRes=-1; }; }else {// Загружаем дллку iRes=FALSE; } ::CoUninitialize(); cs.Unlock(); return iRes; }
void LogManager::Log(const std::string& tag, const std::string& msg, const char* funcName, const char* fileName, unsigned int lineNum) { m_CritSection.Lock(); Tags::iterator findIt = m_Tags.find(tag); if (findIt != m_Tags.end()) { std::string buffer; GetOutputBuffer(buffer, tag, msg, funcName, fileName, lineNum); OutputBufferToLogs(buffer, findIt->second); } m_CritSection.Unlock(); }
CManagerPool &CManagerPool::GetInitInstance() { CCriticalSection Mutex; if(m_PtrInstance == NULL) { //mutex.Lock(); Mutex.Lock(); m_PtrInstance = new CManagerPool(); Mutex.Unlock(); } return *m_PtrInstance; }
//----------------------------------------------------------------------------- // Name: Calculate() // Desc: //----------------------------------------------------------------------------- void COscillDlg::Calculate( void ) { // TRACE( ">>Enter Calculate\r\n" ); TRACE( " Ask->Calc\r\n" ); g_csRWData.Lock(); TRACE( " ->Calc\r\n" ); int nSampPerDiv = (int)( g_sMeasPara.nSampFreq * c_fTbScaleCoef[m_byTbScale] ); m_nSampPerFrame = 12 * nSampPerDiv; // m_nXCnt %= m_nSampPerFrame; m_nXCnt = g_psQueue->num % m_nSampPerFrame; m_nNumOfDiv = ( g_psQueue->num - m_nXCnt ) / nSampPerDiv; m_ctrlSbDrawFrame.SetScrollRange( 0, m_nNumOfDiv ); int nPosition = m_ctrlSbDrawFrame.GetScrollPos(); int ntmp = m_nNumOfDiv - nPosition - ( 12 - m_nXCnt / nSampPerDiv ); if ( 0 < ntmp ) { m_nQueueRearOffset = - m_nXCnt % nSampPerDiv - nSampPerDiv * ntmp; } else { m_nQueueRearOffset = 0; } if ( nPosition == m_nNumOfDiv ) { m_nQueueRearOffset = 0; } m_nXCntOffset = 0; if ( 0 == m_nQueueRearOffset ) { m_nXCntOffset = ( m_nNumOfDiv - nPosition ) * nSampPerDiv; } /* TRACE( "SampPerFrame:%5d DivNum:%3d Pos:%3d NUM:%5d QueueRearOffset:%6d XCnt:%5d XCntOffset:%3d\r\n", m_nSampPerFrame, m_nNumOfDiv, nPosition, g_psQueue->num, m_nQueueRearOffset, m_nXCnt, m_nXCntOffset ); */ TRACE( " <-Calc\r\n" ); g_csRWData.Unlock(); // TRACE( " >>Leave Calculate\r\n" ); }
void OBJECT_WAREHOUSE_CLASS::postSemaphore() // DESCRIPTION : Post the warehouse access semaphore. // PRECONDITIONS : // POSTCONDITIONS : // EXCEPTIONS : // NOTES : //<<=========================================================================== { // post the semaphore WarehouseAccess.Unlock(); }
//Thread safe way to check the done flag, and update the dialog box //appropriately BOOL CLoadLTADlg::IsDone() { BOOL bDone = FALSE; g_ThreadDoneCS.Lock(INFINITE); bDone = sm_bLoadThreadDone; g_ThreadDoneCS.Unlock(); return bDone; }
UINT funcaoThread(LPVOID param) { while (1) { cs.Lock(); for (int i = 0; i < 10; i++) { array[i] = (array[i] + 1) % 10; Sleep(10); } cs.Unlock(); Sleep(100); } return 0; }
long long SharedUtil::GetModuleTickCount64 ( void ) { static CCriticalSection criticalSection; criticalSection.Lock (); if ( !gCurrentTickCount64 ) UpdateModuleTickCount64 (); long long result = gCurrentTickCount64; criticalSection.Unlock (); return result; }
//取1条任务结果 bool CSmartCommunicationDlg::SMT_GetOneTaskResult(SMARTTASKRESULT *mTaskResult) { int nTry=0; list<SMARTTASKRESULT>::iterator LpTaskResult; g_CriticalSectionLock.Lock(); while( ++nTry<3 ) { if( g_LSaveTaskResult.empty() ) { Sleep(1); continue; } break; } if( nTry>=3 ) { g_CriticalSectionLock.Unlock(); return false; } LpTaskResult=g_LSaveTaskResult.begin(); if( LpTaskResult!=NULL ) { strcpy(mTaskResult->ucErrMsg,LpTaskResult->ucErrMsg); strcpy((char*)mTaskResult->ucIP,(char*)LpTaskResult->ucIP); mTaskResult->ResultStatus=LpTaskResult->ResultStatus; mTaskResult->nAcction =LpTaskResult->nAcction; memcpy(&mTaskResult->Pos,&LpTaskResult->Pos,sizeof(SMARTCOMMPACK)); g_LSaveTaskResult.pop_front(); Sleep(1); g_CriticalSectionLock.Unlock(); Sleep(2); return true; } g_CriticalSectionLock.Unlock(); return false; }
void WriteLog (CString &pMessage, LPSTR pDebugMode) { mWriteLog.Lock(); char pFileName[MAX_PATH]= {0}; char path_buffer[_MAX_PATH] = {0}; char drive[_MAX_DRIVE]= {0}; char dir[_MAX_DIR]= {0}; char fname[_MAX_FNAME]= {0}; char ext[_MAX_EXT]= {0}; memset( path_buffer, 0, sizeof( path_buffer ) ); memset( drive, 0, sizeof( drive ) ); memset( dir, 0, sizeof( dir ) ); memset( fname, 0, sizeof( fname ) ); memset( ext, 0, sizeof( ext ) ); GetModuleFileName( 0, path_buffer, 1023 ); _splitpath ( path_buffer, drive, dir, fname, ext ); sprintf(pFileName,"%s%s%s",drive,dir,m_gLogFileName); CFile f; CFileException ex; DWORD dwActual = 0; if( f.Open( pFileName, CFile::modeRead | CFile::shareDenyWrite, &ex) !=0) { dwActual = f.SeekToEnd(); f.Close(); if ( dwActual >= 500000) DeleteFile(pFileName); } FILE *fp = fopen(pFileName, "a"); if (fp) { CString strData; CTime t = CTime::GetCurrentTime(); strData.Format("%s,%s,%s,%s\n",strModule, strVersion,t.Format("%c"),pMessage); fputs(strData,fp); fclose(fp); } mWriteLog.Unlock(); return; }
void LogManager::SetDisplayFlags(const std::string& tag, unsigned char flag) { m_CritSection.Lock(); if (flag != 0) { Tags::iterator findIt = m_Tags.find(tag); if (findIt == m_Tags.end()) m_Tags.insert(std::make_pair(tag, flag)); else findIt->second = flag; } else m_Tags.erase(tag); m_CritSection.Unlock(); }
int main() { AfxBeginThread(funcaoThread,NULL,THREAD_PRIORITY_NORMAL,0,0,NULL); while (1) { cs.Lock(); for (int i = 0; i < 10; i++) { cout << array[i] << ' '; } cout << endl; Sleep(10); cs.Unlock(); } return 0; }
//***************************************************************************************** void BCGPlaySystemSound (int nSound) { if (!CBCGPPopupMenu::IsMenuSound ()) { return; } if (g_nBCGSoundState == BCGSOUND_NOT_STARTED) { if (nSound == BCGSOUND_TERMINATE) { return; } static CCriticalSection cs; cs.Lock (); ASSERT (g_hThreadSound == NULL); //------------------------- // Initialize sound thread: //------------------------- g_hThreadSound = (HANDLE) ::_beginthread (BCGSoundThreadProc, 0, NULL); if (g_hThreadSound > 0 && g_hThreadSound != (HANDLE) -1) { ::SetThreadPriority (g_hThreadSound, THREAD_PRIORITY_BELOW_NORMAL); g_nBCGSoundState = nSound; } else { g_hThreadSound = NULL; } cs.Unlock (); } else { g_nBCGSoundState = nSound; if (g_nBCGSoundState == BCGSOUND_TERMINATE) { //------------------------ // Terminate sound thread: //------------------------ g_hThreadSound = NULL; } } }
void line_socket::clear(std::list<T> queue, CCriticalSection& lock) { T t; std::list<T>::iterator itr; lock.Lock(); for(itr = queue.begin(); itr != queue.end(); ++itr) { t = *itr; if(t != NULL) { delete t; } } queue.clear(); lock.Unlock(); }