Exemplo n.º 1
1
static BOOL WaitComReady(HANDLE hC0C, BOOL ignoreDSR, const BYTE *pAwakSeq)
{
  BOOL waitAwakSeq = (pAwakSeq && *pAwakSeq);
  BOOL waitDSR = (!ignoreDSR && !waitAwakSeq);

  if (!waitAwakSeq && !waitDSR)
    return TRUE;

  enum {
    EVENT_READ,
    EVENT_STAT,
    EVENT_NUM
  };

  HANDLE hEvents[EVENT_NUM];
  OVERLAPPED overlaps[EVENT_NUM];

  if (!PrepareEvents(EVENT_NUM, hEvents, overlaps))
    return FALSE;

  BOOL fault = FALSE;

  if (!SetCommMask(hC0C, EV_DSR)) {
    TraceLastError("WaitComReady(): SetCommMask()");
    fault = TRUE;
  }

  DWORD not_used;

  const BYTE *pAwakSeqNext = pAwakSeq;

  BYTE cbufRead[1];
  BOOL waitingRead = !waitAwakSeq;
  BOOL waitingStat = !waitDSR;

  while (!fault) {
    if (!waitingRead) {
      if (!pAwakSeqNext || !*pAwakSeqNext)
        break;

      if (!ReadFile(hC0C, cbufRead, sizeof(cbufRead), &not_used, &overlaps[EVENT_READ])) {
        if (::GetLastError() != ERROR_IO_PENDING) {
          TraceLastError("WaitComReady(): ReadFile()");
          break;
        }
      }
      waitingRead = TRUE;
    }

    if (!waitingStat) {
      if (!WaitCommEvent(hC0C, &not_used, &overlaps[EVENT_STAT])) {
        if (::GetLastError() != ERROR_IO_PENDING) {
          TraceLastError("WaitComReady(): WaitCommEvent()");
          fault = TRUE;
          break;
        }
      }
      waitingStat = TRUE;

      DWORD stat;

      if (!GetCommModemStatus(hC0C, &stat)) {
        TraceLastError("WaitComReady(): GetCommModemStatus()");
        fault = TRUE;
        break;
      }

      if (stat & MS_DSR_ON) {
        printf("DSR is ON\n");

        Sleep(1000);

        if (!GetCommModemStatus(hC0C, &stat)) {
          TraceLastError("WaitComReady(): GetCommModemStatus()");
          fault = TRUE;
          break;
        }

        if (stat & MS_DSR_ON)
          break;                // OK if DSR is still ON

        printf("DSR is OFF\n");
      }
    }

    if (waitingRead && waitingStat) {
      DWORD done;

      switch (WaitForMultipleObjects(EVENT_NUM, hEvents, FALSE, 5000)) {
      case WAIT_OBJECT_0 + EVENT_READ:
        if (!GetOverlappedResult(hC0C, &overlaps[EVENT_READ], &done, FALSE)) {
          TraceLastError("WaitComReady(): GetOverlappedResult(EVENT_READ)");
          fault = TRUE;
        }
        ResetEvent(hEvents[EVENT_READ]);
        if (done && pAwakSeqNext) {
          if (*pAwakSeqNext == *cbufRead) {
            pAwakSeqNext++;
          } else {
            pAwakSeqNext = pAwakSeq;
            if (*pAwakSeqNext == *cbufRead)
              pAwakSeqNext++;
          }
          printf("Skipped character 0x%02.2X\n", (int)*cbufRead);
        }
        waitingRead = FALSE;
        break;
      case WAIT_OBJECT_0 + EVENT_STAT:
        if (!GetOverlappedResult(hC0C, &overlaps[EVENT_STAT], &not_used, FALSE)) {
          TraceLastError("WaitComReady(): GetOverlappedResult(EVENT_STAT)");
          fault = TRUE;
        }
        waitingStat = FALSE;
        break;
      case WAIT_TIMEOUT:
        break;
      default:
        TraceLastError("WaitComReady(): WaitForMultipleObjects()");
        fault = TRUE;
      }
    }
  }

  CancelIo(hC0C);

  CloseEvents(EVENT_NUM, hEvents);

  printf("WaitComReady() - %s\n", fault ? "FAIL" : "OK");

  return !fault;
}
Exemplo n.º 2
0
DWORD WINAPI ReadDILCANMsg(LPVOID pVoid)
{
    CPARAM_THREADPROC* pThreadParam = (CPARAM_THREADPROC*) pVoid;

    if (pThreadParam != NULL)
    {
        CReadCanMsg* pCurrObj = (CReadCanMsg*) pThreadParam->m_pBuffer;

        if (pCurrObj != NULL)
        {
            pThreadParam->m_unActionCode = INVOKE_FUNCTION; // Set default action
            // Create the action event. In this case this will be used solely for
            // thread exit procedure. The first entry will be used.
            pThreadParam->m_hActionEvent = pCurrObj->m_ahActionEvent[0];
            DWORD dwWaitRet;
            BYTE byHIndex;
            bool bLoopON = true;

            while (bLoopON)
            {
                dwWaitRet = WaitForMultipleObjects(pCurrObj->m_nEvents,
                                                   pCurrObj->m_ahActionEvent, FALSE, INFINITE);
                ///// TEMP : BEGIN
                DWORD dwLLimit = WAIT_OBJECT_0;
                DWORD dwULimit = WAIT_OBJECT_0 + pCurrObj->m_nEvents - 1;
                DWORD dwLLError = WAIT_ABANDONED_0;
                DWORD dwULError = WAIT_ABANDONED_0 + pCurrObj->m_nEvents - 1;

                if ((dwWaitRet >= dwLLimit) && (dwWaitRet <= dwULimit))
                {
                    switch (pThreadParam->m_unActionCode)
                    {
                        case INVOKE_FUNCTION:
                        {
                            //Get the handle's index and pass it
                            byHIndex = (BYTE)(dwWaitRet - WAIT_OBJECT_0);
                            HANDLE hHandleSet = pCurrObj->m_ahActionEvent[byHIndex];
                            BYTE byNodeIndex;

                            if( pCurrObj->m_omHandleToNodeMgrMap.Lookup(hHandleSet, byNodeIndex))
                            {
                                //vRetrieveDataFromBuffer to read from that buffer
                                pCurrObj->vRetrieveDataFromBuffer(byNodeIndex);
                            }

                            //BOOL Result = ResetEvent(hHandleSet);
                            ResetEvent(hHandleSet);
                        }
                        break;

                        case EXIT_THREAD:
                        {
                            bLoopON = false;
                        }
                        break;

                        case INACTION:
                        {
                            // Signal the owner
                            SetEvent(pThreadParam->m_hThread2Owner);
                            Sleep(0);
                            // Wait until owner signals back.
                            WaitForSingleObject(pThreadParam->m_hOwner2Thread, INFINITE);
                            // Signal the owner
                            SetEvent(pThreadParam->m_hThread2Owner);
                            Sleep(0);
                        }
                        break;

                        case CREATE_TIME_MAP:
                        default:
                            break;
                    }
                }
                else if ((dwWaitRet >= dwLLError) && (dwWaitRet <= dwULError))
                {
                    TRACE(_T("Abandoned... %X %d\n"), dwWaitRet, g_unCount++);
                }
                else if ( dwWaitRet == WAIT_TIMEOUT)
                {
                    TRACE(_T("ReadDILCANMsg->WAIT_TIMEOUT %d\n"), g_unCount++);
                }
                else if (dwWaitRet == WAIT_FAILED)
                {
                    TRACE(_T("WAIT_FAILED... %X %d\n"), GetLastError(), g_unCount++);
                }

                ///// TEMP : END
            }

            SetEvent(pThreadParam->hGetExitNotifyEvent());
        }
    }

    return 0;
}
Exemplo n.º 3
0
void MythSystemManager::run(void)
{
    RunProlog();

    LOG(VB_GENERAL, LOG_INFO, "Starting process manager");

    // run_system is set to NULL during shutdown, and we need this thread to
    // exit during shutdown.
    while( run_system )
    {
        // check for any running processes
        m_mapLock.lock();

        if( m_childCount == 0 )
        {
            m_mapLock.unlock();
            usleep( 100000 );
            continue;
        }

        DWORD result = WaitForMultipleObjects( m_childCount, m_children,
                                               FALSE, 100 );

        if ( result == WAIT_TIMEOUT || result == WAIT_FAILED )
        {
            m_mapLock.unlock();
            continue;
        }

        int index = result - WAIT_OBJECT_0;
        if ( index < 0 || index > m_childCount - 1 )
        {
            m_mapLock.unlock();
            continue;
        }
        HANDLE child = m_children[index];

        // pop exited process off managed list, add to cleanup list
        MythSystemWindows  *ms = m_pMap.take(child);
        ChildListRebuild();
        m_mapLock.unlock();

        // Occasionally, the caller has deleted the structure from under
        // our feet.  If so, just log and move on.
        if (!ms)
        {
            LOG(VB_SYSTEM, LOG_ERR,
                QString("Structure for child handle %1 already deleted!")
                .arg((long long)child));
            continue;
        }

        listLock.lock();
        msList.append(ms);

        DWORD               status;
        GetExitCodeProcess( child, &status );

        ms->SetStatus(status);
        LOG(VB_SYSTEM, LOG_INFO,
                QString("Managed child (Handle: %1) has exited! "
                        "command=%2, status=%3, result=%4")
                .arg((long long)child) .arg(ms->GetLogCmd()) .arg(status) 
                .arg(ms->GetStatus()));

        // loop through running processes for any that require action
        MSMap_t::iterator   i;
        time_t              now = time(NULL);

        m_mapLock.lock();
        m_jumpLock.lock();
        for (i = m_pMap.begin(); i != m_pMap.end(); ++i)
        {
            child = i.key();
            ms    = i.value();

            // handle processes beyond marked timeout
            if( ms->m_timeout > 0 && ms->m_timeout < now )
            {
                // issuing KILL signal after TERM failed in a timely manner
                if( ms->GetStatus() == GENERIC_EXIT_TIMEOUT )
                {
                    LOG(VB_SYSTEM, LOG_INFO,
                        QString("Managed child (Handle: %1) timed out, "
                                "issuing KILL signal").arg((long long)child));
                    // Prevent constant attempts to kill an obstinate child
                    ms->m_timeout = 0;
                    ms->Signal(SIGKILL);
                }

                // issuing TERM signal
                else
                {
                    LOG(VB_SYSTEM, LOG_INFO,
                        QString("Managed child (Handle: %1) timed out"
                                ", issuing TERM signal").arg((long long)child));
                    ms->SetStatus( GENERIC_EXIT_TIMEOUT );
                    ms->m_timeout = now + 1;
                    ms->Term();
                }
            }

            if ( m_jumpAbort && ms->GetSetting("AbortOnJump") )
                ms->Term();
        }

        m_jumpAbort = false;
        m_jumpLock.unlock();

        m_mapLock.unlock();

        // hold off unlocking until all the way down here to 
        // give the buffer handling a chance to run before
        // being closed down by signal thread
        listLock.unlock();
    }

    // kick to allow them to close themselves cleanly
    readThread->wake();
    writeThread->wake();

    RunEpilog();
}
Exemplo n.º 4
0
int main(int arc, char **argv)
{
  int bufferSize = atoi(argv[1]);
  int numProducers = atoi(argv[2]);
  int numConsumers = atoi(argv[3]);
  int amountProduced = atoi(argv[4]);

  printf("Buffer size = %d, ", bufferSize);
  printf("number of producer threads = %d, ", numProducers);
  printf("number of consumer threads = %d, ", numConsumers);
  printf("and each producer produces %d\n", amountProduced);

  int *buffer;
  buffer = malloc(bufferSize*sizeof(int));
  buffer[0] = 1;

//  HANDLE producers[1];
//  HANDLE consumers[1];
  HANDLE *producers;
  HANDLE *consumers;
  producers = malloc(numProducers*sizeof(HANDLE));
  consumers = malloc(numConsumers*sizeof(HANDLE));

  full = CreateSemaphore(
		  NULL,
		  0,
		  bufferSize,
		  NULL);
  empty = CreateSemaphore(
		  NULL,
		  bufferSize,
		  bufferSize,
		  NULL);

//  PINFO pInfo[1];
//  CINFO cInfo[1];
  PINFO *pInfo;
  CINFO *cInfo;
  pInfo = malloc(numProducers*sizeof(PINFO));
  cInfo = malloc(numConsumers*sizeof(CINFO));

  for(int i=0; i<numProducers; i++) {
    pInfo[i] = (PINFO)HeapAlloc(GetProcessHeap(),
		    HEAP_ZERO_MEMORY,
		    sizeof(pinfo));
  }
  for(int i=0; i<numConsumers; i++) {
    cInfo[i] = (CINFO)HeapAlloc(GetProcessHeap(),
		    HEAP_ZERO_MEMORY,
		    sizeof(cinfo));
  }

  for(int i=0; i<numProducers; i++) {
    pInfo[i]->threadNumber = i+1;
    pInfo[i]->counter = 0;
    pInfo[i]->toProduce = amountProduced;
    pInfo[i]->buff = buffer;
    pInfo[i]->bufferSize = bufferSize;
  }
  for(int i=0; i<numConsumers; i++) {
    cInfo[i]->threadNumber = i+1;
    cInfo[i]->toConsume = (numProducers * amountProduced) / numConsumers;
    cInfo[i]->buff = buffer;
    cInfo[i]->bufferSize = bufferSize;
  }
  int remainder = (numProducers*amountProduced)%numConsumers;
  for(int i=0; i<remainder; i++) {
    cInfo[i]->toConsume++;
  }
//
  for(int i=0; i<numProducers; i++) {
    producers[i] = CreateThread(NULL,
		    		0,
				producerFunc,
				pInfo[i],
				0,
				NULL);
  }
  for(int i=0; i<numConsumers; i++) {
    consumers[i] = CreateThread(NULL,
		    		0,
				consumerFunc,
				cInfo[i],
				0,
				NULL);
  }

  WaitForMultipleObjects(numProducers, producers, TRUE, INFINITE);
  WaitForMultipleObjects(numConsumers, consumers, TRUE, INFINITE);

  CloseHandle(full);
  CloseHandle(empty);
  CloseHandle(mutex);

  printf("***All jobs finished***\n");
}
Exemplo n.º 5
0
static void prvProcessSimulatedInterrupts( void )
{
uint32_t ulSwitchRequired, i;
xThreadState *pxThreadState;
void *pvObjectList[ 2 ];

	/* Going to block on the mutex that ensured exclusive access to the simulated
	interrupt objects, and the event that signals that a simulated interrupt
	should be processed. */
	pvObjectList[ 0 ] = pvInterruptEventMutex;
	pvObjectList[ 1 ] = pvInterruptEvent;

	/* Create a pending tick to ensure the first task is started as soon as
	this thread pends. */
	ulPendingInterrupts |= ( 1 << portINTERRUPT_TICK );
	SetEvent( pvInterruptEvent );

	xPortRunning = pdTRUE;

	for(;;)
	{
		WaitForMultipleObjects( sizeof( pvObjectList ) / sizeof( void * ), pvObjectList, TRUE, INFINITE );

		/* Used to indicate whether the simulated interrupt processing has
		necessitated a context switch to another task/thread. */
		ulSwitchRequired = pdFALSE;

		/* For each interrupt we are interested in processing, each of which is
		represented by a bit in the 32bit ulPendingInterrupts variable. */
		for( i = 0; i < portMAX_INTERRUPTS; i++ )
		{
			/* Is the simulated interrupt pending? */
			if( ulPendingInterrupts & ( 1UL << i ) )
			{
				/* Is a handler installed? */
				if( ulIsrHandler[ i ] != NULL )
				{
					/* Run the actual handler. */
					if( ulIsrHandler[ i ]() != pdFALSE )
					{
						ulSwitchRequired |= ( 1 << i );
					}
				}

				/* Clear the interrupt pending bit. */
				ulPendingInterrupts &= ~( 1UL << i );
			}
		}

		if( ulSwitchRequired != pdFALSE )
		{
			void *pvOldCurrentTCB;

			pvOldCurrentTCB = pxCurrentTCB;

			/* Select the next task to run. */
			vTaskSwitchContext();

			/* If the task selected to enter the running state is not the task
			that is already in the running state. */
			if( pvOldCurrentTCB != pxCurrentTCB )
			{
				/* Suspend the old thread. */
				pxThreadState = ( xThreadState *) *( ( uint32_t * ) pvOldCurrentTCB );
				SuspendThread( pxThreadState->pvThread );

				/* Obtain the state of the task now selected to enter the
				Running state. */
				pxThreadState = ( xThreadState * ) ( *( uint32_t *) pxCurrentTCB );
				ResumeThread( pxThreadState->pvThread );
			}
		}

		ReleaseMutex( pvInterruptEventMutex );
	}
}
Exemplo n.º 6
0
/***************************************************************************
 * 				MCIAVI_mciPlay			[internal]
 */
static	DWORD	MCIAVI_mciPlay(UINT wDevID, DWORD dwFlags, LPMCI_PLAY_PARMS lpParms)
{
    WINE_MCIAVI *wma;
    DWORD		frameTime;
    DWORD		dwRet;
    LPWAVEHDR		waveHdr = NULL;
    unsigned		i, nHdr = 0;
    DWORD		dwFromFrame, dwToFrame;
    DWORD		numEvents = 1;
    HANDLE		events[2];

    TRACE("(%04x, %08X, %p)\n", wDevID, dwFlags, lpParms);

    if (lpParms == NULL)	return MCIERR_NULL_PARAMETER_BLOCK;

    wma = MCIAVI_mciGetOpenDev(wDevID);
    if (wma == NULL)		return MCIERR_INVALID_DEVICE_ID;
    if (dwFlags & MCI_DGV_PLAY_REVERSE) return MCIERR_UNSUPPORTED_FUNCTION;
    if (dwFlags & MCI_TEST)	return 0;

    EnterCriticalSection(&wma->cs);

    if (!wma->hFile)
    {
        LeaveCriticalSection(&wma->cs);
        return MCIERR_FILE_NOT_FOUND;
    }
    if (!wma->hWndPaint)
    {
        LeaveCriticalSection(&wma->cs);
        return MCIERR_NO_WINDOW;
    }

    LeaveCriticalSection(&wma->cs);

    if (!(dwFlags & MCI_WAIT))
        return MCIAVI_mciPlay_async(wma, dwFlags, lpParms);

    if (!(GetWindowLongW(wma->hWndPaint, GWL_STYLE) & WS_VISIBLE))
        ShowWindow(wma->hWndPaint, SW_SHOWNA);

    EnterCriticalSection(&wma->cs);

    dwFromFrame = wma->dwCurrVideoFrame;
    dwToFrame = wma->dwPlayableVideoFrames - 1;

    if (dwFlags & MCI_FROM) {
	dwFromFrame = MCIAVI_ConvertTimeFormatToFrame(wma, lpParms->dwFrom);
    }
    if (dwFlags & MCI_TO) {
	dwToFrame = MCIAVI_ConvertTimeFormatToFrame(wma, lpParms->dwTo);
    }
    if (dwToFrame >= wma->dwPlayableVideoFrames)
	dwToFrame = wma->dwPlayableVideoFrames - 1;

    TRACE("Playing from frame=%u to frame=%u\n", dwFromFrame, dwToFrame);

    wma->dwCurrVideoFrame = dwFromFrame;
    wma->dwToVideoFrame = dwToFrame;

    /* if already playing exit */
    if (wma->dwStatus == MCI_MODE_PLAY)
    {
        LeaveCriticalSection(&wma->cs);
        SetEvent(wma->ack_event);
        return 0;
    }

    if (wma->dwToVideoFrame <= wma->dwCurrVideoFrame)
    {
        dwRet = 0;
        SetEvent(wma->ack_event);
        goto mci_play_done;
    }

    wma->dwStatus = MCI_MODE_PLAY;
    /* signal the state change */
    SetEvent(wma->ack_event);

    if (dwFlags & (MCI_DGV_PLAY_REPEAT|MCI_MCIAVI_PLAY_WINDOW|MCI_MCIAVI_PLAY_FULLSCREEN))
	FIXME("Unsupported flag %08x\n", dwFlags);

    /* time is in microseconds, we should convert it to milliseconds */
    frameTime = (wma->mah.dwMicroSecPerFrame + 500) / 1000;

    events[0] = wma->hStopEvent;
    if (wma->lpWaveFormat) {
       if (MCIAVI_OpenAudio(wma, &nHdr, &waveHdr) != 0)
        {
            /* can't play audio */
            HeapFree(GetProcessHeap(), 0, wma->lpWaveFormat);
            wma->lpWaveFormat = NULL;
        }
       else
       {
            /* fill the queue with as many wave headers as possible */
            MCIAVI_PlayAudioBlocks(wma, nHdr, waveHdr);
            events[1] = wma->hEvent;
            numEvents = 2;
       }
    }

    while (wma->dwStatus == MCI_MODE_PLAY)
    {
        HDC hDC;
        DWORD tc, delta;
        DWORD ret;

	tc = GetTickCount();

        hDC = wma->hWndPaint ? GetDC(wma->hWndPaint) : 0;
        if (hDC)
        {
            MCIAVI_PaintFrame(wma, hDC);
            ReleaseDC(wma->hWndPaint, hDC);
        }

        if (wma->lpWaveFormat)
	    MCIAVI_PlayAudioBlocks(wma, nHdr, waveHdr);

	delta = GetTickCount() - tc;
	if (delta < frameTime)
            delta = frameTime - delta;
        else
            delta = 0;

        LeaveCriticalSection(&wma->cs);
        ret = WaitForMultipleObjects(numEvents, events, FALSE, delta);
        EnterCriticalSection(&wma->cs);
        if (ret == WAIT_OBJECT_0 || wma->dwStatus != MCI_MODE_PLAY) break;

       if (wma->dwCurrVideoFrame < dwToFrame)
           wma->dwCurrVideoFrame++;
        else
            break;
    }

    if (wma->lpWaveFormat) {
       while (wma->dwEventCount != nHdr - 1)
        {
            LeaveCriticalSection(&wma->cs);
            Sleep(100);
            EnterCriticalSection(&wma->cs);
        }

	/* just to get rid of some race conditions between play, stop and pause */
	LeaveCriticalSection(&wma->cs);
	waveOutReset(wma->hWave);
	EnterCriticalSection(&wma->cs);

	for (i = 0; i < nHdr; i++)
	    waveOutUnprepareHeader(wma->hWave, &waveHdr[i], sizeof(WAVEHDR));
    }

    dwRet = 0;

    if (wma->lpWaveFormat) {
	HeapFree(GetProcessHeap(), 0, waveHdr);

	if (wma->hWave) {
	    LeaveCriticalSection(&wma->cs);
	    waveOutClose(wma->hWave);
	    EnterCriticalSection(&wma->cs);
	    wma->hWave = 0;
	}
	CloseHandle(wma->hEvent);
    }

mci_play_done:
    wma->dwStatus = MCI_MODE_STOP;

    if (dwFlags & MCI_NOTIFY) {
	TRACE("MCI_NOTIFY_SUCCESSFUL %08lX !\n", lpParms->dwCallback);
	mciDriverNotify(HWND_32(LOWORD(lpParms->dwCallback)),
                       wDevID, MCI_NOTIFY_SUCCESSFUL);
    }
    LeaveCriticalSection(&wma->cs);
    return dwRet;
}
Exemplo n.º 7
0
int MetaStatsCommand::process(vector<SharedRAbundVector*>& thisLookUp){
	try {
		
		
				if(processors == 1){
					driver(0, namesOfGroupCombos.size(), thisLookUp);
				}else{
					int process = 1;
					vector<int> processIDS;
		#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
					//loop through and create all the processes you want
					while (process != processors) {
						int pid = fork();
			
						if (pid > 0) {
							processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
							process++;
						}else if (pid == 0){
							driver(lines[process].start, lines[process].num, thisLookUp);
							exit(0);
						}else { 
							m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
							for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
							exit(0);
						}
					}
					
					//do my part
					driver(lines[0].start, lines[0].num, thisLookUp);
		
					//force parent to wait until all the processes are done
					for (int i=0;i<(processors-1);i++) { 
						int temp = processIDS[i];
						wait(&temp);
					}
        #else
                    
                    //////////////////////////////////////////////////////////////////////////////////////////////////////
                    //Windows version shared memory, so be careful when passing variables through the summarySharedData struct. 
                    //Above fork() will clone, so memory is separate, but that's not the case with windows, 
                    //Taking advantage of shared memory to pass results vectors.
                    //////////////////////////////////////////////////////////////////////////////////////////////////////
                    
                    vector<metastatsData*> pDataArray; 
                    DWORD   dwThreadIdArray[processors-1];
                    HANDLE  hThreadArray[processors-1]; 
                    
                    //Create processor worker threads.
                    for( int i=1; i<processors; i++ ){
                        
                        //make copy of lookup so we don't get access violations
                        vector<SharedRAbundVector*> newLookup;
                        vector<string> designMapGroups;
                        for (int k = 0; k < thisLookUp.size(); k++) {
                            SharedRAbundVector* temp = new SharedRAbundVector();
                            temp->setLabel(thisLookUp[k]->getLabel());
                            temp->setGroup(thisLookUp[k]->getGroup());
                            newLookup.push_back(temp);
                            designMapGroups.push_back(designMap->getGroup(thisLookUp[k]->getGroup()));
                        }
                        
                        //for each bin
                        for (int k = 0; k < thisLookUp[0]->getNumBins(); k++) {
                            if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) {  delete newLookup[j];  } return 0; }
                            for (int j = 0; j < thisLookUp.size(); j++) { newLookup[j]->push_back(thisLookUp[j]->getAbundance(k), thisLookUp[j]->getGroup()); }
                        }
                        
                        // Allocate memory for thread data.
                        metastatsData* tempSum = new metastatsData(sharedfile, outputDir, m, lines[i].start, lines[i].num, namesOfGroupCombos, newLookup, designMapGroups, iters, threshold);
                        pDataArray.push_back(tempSum);
                        processIDS.push_back(i);
                        
                        hThreadArray[i-1] = CreateThread(NULL, 0, MyMetastatsThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);   
                    }
                    
                    //do my part
					driver(lines[0].start, lines[0].num, thisLookUp);
                    
                    //Wait until all threads have terminated.
                    WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
                    
                    //Close all thread handles and free memory allocations.
                    for(int i=0; i < pDataArray.size(); i++){
                        if (pDataArray[i]->count != (pDataArray[i]->num)) {
                            m->mothurOut("[ERROR]: process " + toString(i) + " only processed " + toString(pDataArray[i]->count) + " of " + toString(pDataArray[i]->num) + " groups assigned to it, quitting. \n"); m->control_pressed = true; 
                        }
                        for (int j = 0; j < pDataArray[i]->thisLookUp.size(); j++) {  delete pDataArray[i]->thisLookUp[j];  } 
                        for (int j = 0; j < pDataArray[i]->outputNames.size(); j++) {  
                            outputNames.push_back(pDataArray[i]->outputNames[j]);
                            outputTypes["metastats"].push_back(pDataArray[i]->outputNames[j]);
                        }
                                                
                        CloseHandle(hThreadArray[i]);
                        delete pDataArray[i];
                    }
        #endif

				}
		
		return 0;
		
	}
	catch(exception& e) {
		m->errorOut(e, "MetaStatsCommand", "process");
		exit(1);
	}
}
Exemplo n.º 8
0
STDMETHODIMP CWinRobotService::GetActiveConsoleSession(IUnknown** ppSession)
{
	TrackDebugOut;
	if(ppSession == 0) 
	{
		DebugOutF(filelog::log_error,"GetActiveConsoleSession failed,ppSession == null");
		return E_POINTER;
	}
	*ppSession = 0 ;

	// if has exist,determine whether the process has been closed.
	CAutoLockEx<CCrtSection> lock(m_csLock);
	static Kernel32Dll dll;
	DWORD sid = dll.WTSGetActiveConsoleSessionId();

	{
		CAutoLock<CCrtSection> lock2(m_csLockSessions);
		SESSIONS::iterator it = m_sessions.find(sid);
		if ( it != m_sessions.end() )
		{
			CRefObj< CReference_T<SESSION> >  sn = it->second;
			_ASSERT(sn->pSession);
			if ( sn->IsOK() )
			{
				HRESULT hr = sn->pSession->QueryInterface(__uuidof(IWinRobotSession),(void**)ppSession);
				if(SUCCEEDED(hr))
				{
					DebugOutF(filelog::log_info,"GetActiveConsoleSession %d ok",sid);
				}
				else
				{
					DebugOutF(filelog::log_error,"GetActiveConsoleSession %d failed with 0x%x ",sid,hr);
				}
				return hr;
			}
		}
	}
	// else,create a new child process,and then wait for complete
	
	HANDLE hProcess = CreateChildProcess(sid);
	if(!hProcess)
	{
		return E_UNEXPECTED;
	}
	ResetEvent(m_hNewReg);
	HANDLE hd[] = {m_hExit,m_hNewReg,hProcess};

	HRESULT hr = S_OK;
	/*while (SUCCEEDED(hr))*/
	{
		DWORD res = WaitForMultipleObjects(RTL_NUMBER_OF(hd),hd,FALSE,-1);
		if( (res < WAIT_OBJECT_0) || (res>=res+RTL_NUMBER_OF(hd) ) )
		{
			hr = E_UNEXPECTED;
			DebugOutF(filelog::log_error,"WaitForMultipleObjects failed with %d ",GetLastError() );
			
		}
		else if (hd[res-WAIT_OBJECT_0] == m_hExit)
		{
			DebugOutF(filelog::log_error,"GetActiveConsoleSession failed,CWinRobotService stopped");
			hr = E_UNEXPECTED;
			//break;
		}
		else if(hd[res-WAIT_OBJECT_0] == m_hNewReg)
		{
			CAutoLock<CCrtSection> lock2(m_csLockSessions);
			for (SESSIONS::iterator it = m_sessions.begin();
				it != m_sessions.end();
				it++)
			{
				if(GetProcessId(hProcess) == GetProcessId(it->second->m_hProcess)){
					CRefObj< CReference_T<SESSION> >  sn = it->second;
					_ASSERT(sn->pSession);
					//! this will be a bug !
					// sometimes CreateChildProcess failed on the specified session with error 233,
					// then we CreateChildProcess on session 0 to make sure we can capture something,
					// so the sid will be not the specified session.
					if(it->first != sid){
						m_sessions.erase(it);
						m_sessions[sid] = sn;
					}
					if ( sn->IsOK() )
					{
						hr = sn->pSession->QueryInterface(__uuidof(IWinRobotSession),(void**)ppSession);

						if(SUCCEEDED(hr))
						{
							DebugOutF(filelog::log_info,"GetActiveConsoleSession %d ok",sid);
						}
						else
						{
							DebugOutF(filelog::log_error,"GetActiveConsoleSession %d failed with 0x%x ",sid,hr);
						}
						break;
					}
					else
					{
						DebugOutF(filelog::log_error,"GetActiveConsoleSession failed, process has end");
						hr = E_UNEXPECTED;
						break;
					}
				}
			}
			
		}
		else if(hd[res-WAIT_OBJECT_0] == hProcess)
		{
			DebugOutF(filelog::log_error,"GetActiveConsoleSession failed,process has end");
			hr = E_UNEXPECTED;
			//break;
		}else{
			DebugOutF(filelog::log_error,"GetActiveConsoleSession failed");
			hr = E_UNEXPECTED;
		}
	}
	CloseHandle(hProcess);
	return hr;// should never be here
}
// vlakno na output
DWORD CAMROutputPin::ThreadProc()
{
	while (true) {
		DWORD cmd = GetRequest();
		switch (cmd) {
			case CMD_EXIT:		Reply(0); return 0; break;
			case CMD_STOP:
				{
					Reply(0); 
				}
				break;
			case CMD_RUN:
				{
					Reply(0);
					if (!IsConnected()) {
						break;
					}

					// deliver packets
					DWORD	cmd2;
					BOOL	is_first = true;
					DataPacketAMR	*packet;
					HRESULT	hr;

					do {
						if (ev_abort.Check()) {
							break;
						}
						hr = NOERROR;
					
						HANDLE	events[] = { ev_can_read, ev_abort};
						DWORD	ret = WaitForMultipleObjects(2, events, FALSE, 10);

						if (ret == WAIT_OBJECT_0) {
							// look for new packet in queue
							{
								CAutoLock	lck(&lock_queue);
								packet = queue.RemoveHead();
								if (queue.IsEmpty()) {
									ev_can_read.Reset();
								}

								// allow buffering
								if (GetBufferTime_MS() < buffer_time_ms) {
									ev_can_write.Set();
								}
							}

							// bud dorucime End Of Stream, alebo packet
							if (packet->type == DataPacketAMR::PACKET_TYPE_EOS) {
								DeliverEndOfStream();
							} else if (packet->type == DataPacketAMR::PACKET_TYPE_NEW_SEGMENT) {
								hr = DeliverNewSegment(packet->rtStart, packet->rtStop, packet->rate);
							} else if (packet->type == DataPacketAMR::PACKET_TYPE_DATA) {
								hr = DeliverDataPacketAMR(*packet);
							}					

							delete packet;

							if (FAILED(hr)) {
								break;
							}
						}
					} while (!CheckRequest(&cmd2));
				}
				break;
			default:
				Reply(E_UNEXPECTED); 
				break;
		}
	}
	return 0;
}
Exemplo n.º 10
0
CCodec_BC6H::~CCodec_BC6H()
{
    if (m_LibraryInitialized)
    {

        if (m_Use_MultiThreading)
        {
            // Tell all the live threads that they can exit when they have finished any current work
            for(int i=0; i < m_LiveThreads; i++)
            {
                // If a thread is in the running state then we need to wait for it to finish
                // any queued work from the producer before we can tell it to exit.
                //
                // If we don't wait then there is a race condition here where we have
                // told the thread to run but it hasn't yet been scheduled - if we set
                // the exit flag before it runs then its block will not be processed.
#pragma warning(push)
#pragma warning(disable:4127) //warning C4127: conditional expression is constant
                while(1)
                {
                    if (g_BC6EncodeParameterStorage == NULL) break;
                    if(g_BC6EncodeParameterStorage[i].run != TRUE)
                    {
                        break;
                    }
                }
#pragma warning(pop)
                // Signal to the thread that it can exit
                g_BC6EncodeParameterStorage[i].exit = TRUE;
            }

            // Now wait for all threads to have exited
            if(m_LiveThreads > 0)
            {
                WaitForMultipleObjects(m_LiveThreads,
                                       m_EncodingThreadHandle,
                                       true,
                                       INFINITE);
            }

        } // MultiThreading

        for(int i=0; i < m_LiveThreads; i++)
        {
            if(m_EncodingThreadHandle[i])
            {
                CloseHandle(m_EncodingThreadHandle[i]);
            }
            m_EncodingThreadHandle[i] = 0;
        }

        delete[] m_EncodingThreadHandle;
        m_EncodingThreadHandle = NULL;

        delete[] g_BC6EncodeParameterStorage;
        g_BC6EncodeParameterStorage = NULL;

        
        for(int i=0; i < m_NumEncodingThreads; i++)
        {
            if (m_encoder[i])
            {
                delete m_encoder[i];
                m_encoder[i] = NULL;
            }
        }

        if (m_decoder)
        {
            delete m_decoder;
            m_decoder = NULL;
        }

        Quant_DeInit();
        m_LibraryInitialized = false;
    }
}
Exemplo n.º 11
0
Arquivo: nmakehlp.c Projeto: das/tcl
int
CheckForLinkerFeature(
    const char *option)
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    SECURITY_ATTRIBUTES sa;
    DWORD threadID;
    char msg[300];
    BOOL ok;
    HANDLE hProcess, h, pipeThreads[2];
    char cmdline[100];

    hProcess = GetCurrentProcess();

    ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
    ZeroMemory(&si, sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);
    si.dwFlags   = STARTF_USESTDHANDLES;
    si.hStdInput = INVALID_HANDLE_VALUE;

    ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES));
    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;

    /*
     * Create a non-inheritible pipe.
     */

    CreatePipe(&Out.pipe, &h, &sa, 0);

    /*
     * Dupe the write side, make it inheritible, and close the original.
     */

    DuplicateHandle(hProcess, h, hProcess, &si.hStdOutput, 0, TRUE,
	    DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);

    /*
     * Same as above, but for the error side.
     */

    CreatePipe(&Err.pipe, &h, &sa, 0);
    DuplicateHandle(hProcess, h, hProcess, &si.hStdError, 0, TRUE,
	    DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);

    /*
     * Base command line.
     */

    lstrcpy(cmdline, "link.exe -nologo ");

    /*
     * Append our option for testing.
     */

    lstrcat(cmdline, option);

    ok = CreateProcess(
	    NULL,	    /* Module name. */
	    cmdline,	    /* Command line. */
	    NULL,	    /* Process handle not inheritable. */
	    NULL,	    /* Thread handle not inheritable. */
	    TRUE,	    /* yes, inherit handles. */
	    DETACHED_PROCESS, /* No console for you. */
	    NULL,	    /* Use parent's environment block. */
	    NULL,	    /* Use parent's starting directory. */
	    &si,	    /* Pointer to STARTUPINFO structure. */
	    &pi);	    /* Pointer to PROCESS_INFORMATION structure. */

    if (!ok) {
	DWORD err = GetLastError();
	int chars = snprintf(msg, sizeof(msg) - 1,
		"Tried to launch: \"%s\", but got error [%u]: ", cmdline, err);

	FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS|
		FORMAT_MESSAGE_MAX_WIDTH_MASK, 0L, err, 0, (LPVOID)&msg[chars],
		(300-chars), 0);
	WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg,lstrlen(msg), &err,NULL);
	return 2;
    }

    /*
     * Close our references to the write handles that have now been inherited.
     */

    CloseHandle(si.hStdOutput);
    CloseHandle(si.hStdError);

    WaitForInputIdle(pi.hProcess, 5000);
    CloseHandle(pi.hThread);

    /*
     * Start the pipe reader threads.
     */

    pipeThreads[0] = CreateThread(NULL, 0, ReadFromPipe, &Out, 0, &threadID);
    pipeThreads[1] = CreateThread(NULL, 0, ReadFromPipe, &Err, 0, &threadID);

    /*
     * Block waiting for the process to end.
     */

    WaitForSingleObject(pi.hProcess, INFINITE);
    CloseHandle(pi.hProcess);

    /*
     * Wait for our pipe to get done reading, should it be a little slow.
     */

    WaitForMultipleObjects(2, pipeThreads, TRUE, 500);
    CloseHandle(pipeThreads[0]);
    CloseHandle(pipeThreads[1]);

    /*
     * Look for the commandline warning code in the stderr stream.
     */

    return !(strstr(Out.buffer, "LNK1117") != NULL ||
	    strstr(Err.buffer, "LNK1117") != NULL ||
	    strstr(Out.buffer, "LNK4044") != NULL ||
	    strstr(Err.buffer, "LNK4044") != NULL);
}
Exemplo n.º 12
0
void DXInput::ProcessInput()
{
    traceIn(DXInput::ProcessInput);

    DWORD   dwEventStatus;
    HRESULT result;

    while(!bInputExiting && ((dwEventStatus = WaitForMultipleObjects(2, InputEvents, FALSE, 0)) != WAIT_TIMEOUT))
    {
        if(bInputExiting)
            break;

        if(dwEventStatus == KEYBOARD_EVENT_TRIGGER)
        {
            unsigned char newkeys[256];

            if((result = diKeyboard->GetDeviceState(256, newkeys)) != DI_OK)
            {
                if((result != DIERR_INPUTLOST) && (result != DIERR_OTHERAPPHASPRIO) && (result != DIERR_NOTACQUIRED))
                    AppWarning(TEXT("DInput: Could not get keyboard device state"));
                continue;
            }

            if(bIgnoreNextKeyFrame)
            {
                bIgnoreNextKeyFrame = FALSE;
                continue;
            }

            /*newkeys[DIK_LSHIFT] |= newkeys[DIK_RSHIFT];
            newkeys[DIK_RSHIFT] = 0;

            newkeys[DIK_LCONTROL] |= newkeys[DIK_RCONTROL];
            newkeys[DIK_RCONTROL] = 0;*/

            for(int i=0; i<256; i++)
            {
                if(keys[i] != newkeys[i])
                {
                    if(!curKBHandler.Num() || !curKBHandler[0]->bCharInput)
                    {
                        if(curKBHandler.Num())
                            curKBHandler[0]->KeyboardHandler(GetDIKInputCode(i), ((newkeys[i] & 0x80) != 0));
                        else
                            ControlWindow::WindowKeyboardHandler(GetDIKInputCode(i), ((newkeys[i] & 0x80) != 0), GS);
                    }
                    keys[i] = newkeys[i];
                }
            }
        }
        else if(dwEventStatus == MOUSE_EVENT_TRIGGER)
        {
            DIMOUSESTATE newMouseState; //6x25

            if((result = diMouse->GetDeviceState(sizeof(DIMOUSESTATE), &newMouseState)) != DI_OK)
            {
                if((result != DIERR_INPUTLOST) && (result != DIERR_OTHERAPPHASPRIO) && (result != DIERR_NOTACQUIRED))
                    AppWarning(TEXT("DInput: Could not get keyboard device state"));
                continue;
            }

            if((newMouseState.lX != 0) || (newMouseState.lY != 0))
            {
                if(curMouseHandler.Num())
                    curMouseHandler[0]->MouseHandler(MOUSE_MOVE, curMouseButtonStates, MAKELPARAM(newMouseState.lX, mousestate.lY));
                else
                    ControlWindow::WindowMouseHandler(MOUSE_MOVE, curMouseButtonStates, MAKELPARAM(newMouseState.lX, mousestate.lY), GS);
            }
            if(newMouseState.lZ != 0)
            {
                if(curMouseHandler.Num())
                    curMouseHandler[0]->MouseHandler(MOUSE_WHEEL, curMouseButtonStates, (int)newMouseState.lZ);
                else
                     ControlWindow::WindowMouseHandler(MOUSE_WHEEL, curMouseButtonStates, (int)newMouseState.lZ, GS);
            }
            if(newMouseState.rgbButtons[0] != mousestate.rgbButtons[0])
            {
                if(newMouseState.rgbButtons[0])
                    curMouseButtonStates |= STATE_LBUTTONDOWN;
                else
                    curMouseButtonStates &= ~STATE_LBUTTONDOWN;

                BOOL bDown = ((curMouseButtonStates & STATE_LBUTTONDOWN) != 0);
                if(curMouseHandler.Num())
                    curMouseHandler[0]->MouseHandler(MOUSE_LEFTBUTTON, curMouseButtonStates, (int)bDown);
                else
                     ControlWindow::WindowMouseHandler(MOUSE_LEFTBUTTON, curMouseButtonStates, (int)bDown, GS);
            }
            if(newMouseState.rgbButtons[1] != mousestate.rgbButtons[1])
            {
                if(newMouseState.rgbButtons[1])
                    curMouseButtonStates |= STATE_RBUTTONDOWN;
                else
                    curMouseButtonStates &= ~STATE_RBUTTONDOWN;

                BOOL bDown = ((curMouseButtonStates & STATE_RBUTTONDOWN) != 0);
                if(curMouseHandler.Num())
                    curMouseHandler[0]->MouseHandler(MOUSE_RIGHTBUTTON, curMouseButtonStates, (int)bDown);
                else
                     ControlWindow::WindowMouseHandler(MOUSE_RIGHTBUTTON, curMouseButtonStates, (int)bDown, GS);
            }
            if(newMouseState.rgbButtons[2] != mousestate.rgbButtons[2])
            {
                if(newMouseState.rgbButtons[2])
                    curMouseButtonStates |= STATE_MBUTTONDOWN;
                else
                    curMouseButtonStates &= ~STATE_MBUTTONDOWN;

                BOOL bDown = ((curMouseButtonStates & STATE_MBUTTONDOWN) != 0);
                if(curMouseHandler.Num())
                    curMouseHandler[0]->MouseHandler(MOUSE_MIDDLEBUTTON, curMouseButtonStates, (int)bDown);
                else
                     ControlWindow::WindowMouseHandler(MOUSE_MIDDLEBUTTON, curMouseButtonStates, (int)bDown, GS);
            }

            mcpy(&mousestate, &newMouseState, sizeof(DIMOUSESTATE));
        }
    }

    Super::ProcessInput();

    //return 0;

    traceOut;
}
Exemplo n.º 13
0
LRESULT CALLBACK WndProc(HWND h, UINT im, WPARAM wp, LPARAM lp) {
	switch (im) {
	case WM_CREATE: {
		HANDLE mailslot;
		DWORD recvSize;
		
		// 메일슬롯 만들기
		mailslot = CreateFile(MSLOT, GENERIC_WRITE, FILE_SHARE_READ, NULL,
			OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

		if (mailslot == INVALID_HANDLE_VALUE) {
			mailslot = CreateMailslot(MSLOT, 0, 0, NULL);
			isServer = true;
		}
		else {
			isServer = false;
		}

		// Random Seed
		srand((unsigned)time(NULL));

		// 0.1초마다 갱신
		SetTimer(h, 0, 100, NULL);

		// 화면 얻기
		RECT rect;
		GetClientRect(h, &rect);
		width = rect.right - rect.left;
		height = rect.bottom - rect.top;

		// 세마포어
		sep = CreateSemaphore(NULL, 1, 1, L"");
		
		// 공 45개 만들기
		// 서버일 경우
		if (isServer) {
			for (int i = 0; i < 45; i++) {
				balls[i].id = i + 1;
				balls[i].x = 50 + 100 * (i % 9);			// row
				balls[i].y = 50 + 100 * (i / 9);		// column
				balls[i].hdc = hdc;
				balls[i].sep = sep;
				balls[i].h = h;

				// 랜덤 이동 변수 -1 ~ 1
				randomX[i] = 3 * ((rand() % 2) * 2 - 1);
				randomY[i] = 3 * ((rand() % 2) * 2 - 1);
			}
		}
		// 클라이언트 일 경우
		else {
			for (int i = 0; i < 7; i++) {
				balls[i].id = (rand() % 45) + 1;
				for (int j = 0; j < i; j++) {
					if (balls[j].id == balls[i].id) {
						i--;
						break;
					}
				}
				balls[i].h = h;
				balls[i].hdc = hdc;
				balls[i].sep = sep;
				balls[i].x = 200 + 100 * i;
				balls[i].y = height / 2;

				// 랜덤 이동 변수 -1 ~ 1
				randomX[i] = (rand() % 2);
				randomY[i] = (rand() % 2);
			}
		}
		break;
	}
	case WM_TIMER: {
		// 서버일 경우
		if (isServer) {
			for (int i = 0; i < 45; i++) {
				balls[i].x += randomX[i];
				balls[i].y += randomY[i];
				if (balls[i].x < 0 || balls[i].x > width) {
					randomX[i] *= -1;
				}
				if (balls[i].y<0 || balls[i].y>height) {
					randomY[i] *= -1;
				}
				threadArray[i] = CreateThread(NULL, 0, ThreadFunc, (LPVOID)&balls[i], 0, &threadID);
			}

			// THREAD JOIN
			if (threadArray != NULL) {
				WaitForMultipleObjects(45, threadArray, TRUE, INFINITE);
			}
		}
		// 클라이언트인 경우
		else {
			for (int i = 0; i < 7; i++) {
				balls[i].x += randomX[i];
				balls[i].y += randomY[i];
				threadArray[i] = CreateThread(NULL, 0, ThreadFunc, (LPVOID)&balls[i], 0, &threadID);
				Sleep(1000);
			}
		}
		break;
	}
	case WM_LBUTTONDOWN:
		if (isServer) {
			// 자식 프로세스 생성
			wchar_t title[10] = L"Lotto.exe";
			STARTUPINFO si = { 0, };
			CreateProcess(NULL, title, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi);
		}
		else {
			// 종료
			PostQuitMessage(0);
		}
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	}
	return(DefWindowProc(h, im, wp, lp));
}
Exemplo n.º 14
0
DWORD WINAPI SearchWorkThreadMgrProc(LPVOID lpParm)
{
	CQuickSearchDlg * lpDlg = (CQuickSearchDlg *)lpParm;
	if (lpDlg == NULL)
	{
		lpDlg->NotifyStatusMsg(_T("线程的非法引用!请退出程序,然后重试。"));
		return ERROR_INVALID_PARAMETER;
	}
	if (!EnablePrivilege(SE_DEBUG_NAME, TRUE))
	{
		lpDlg->NotifyStatusMsg(_T("提权失败!"));
		return ERROR_ACCESS_DENIED;
	}
	for (int i = 0; lpDlg->GetSafeHwnd() == NULL && i < 10; i++)
		Sleep(100);

	lpDlg->NotifyStatusMsg(_T("就绪..."));
	while (TRUE)
	{
		TCHAR szMsg[nMSG_SIZE] = { 0 };
		ULONG nFoundedCont = 0;

		WaitForSingleObject(g_hSearchEvent, INFINITE);
		if (WaitForSingleObject(g_hQuitEvent, 50) == WAIT_OBJECT_0)
		{
			// 执行搜索之前检测有无退出信号
			break;
		}

		lpDlg->InitList();
		SEARCH_PROGRRESS_INFO spi[26] = { 0 };
		for (short i = 0; i < 26; i++)
		{
			spi[i].m_nFoundCount = 0;
			spi[i].m_nViewCount = 0;
			spi[i].m_lpDlg = lpDlg;
			spi[i].m_Update = update;
			ParseSearchObject(lpDlg->GetSearchString().GetBuffer(), spi[i].m_vecSearchStrings);
			lpDlg->GetSearchString().ReleaseBuffer();
		}

		g_nTotalFound = 0;			// 已经找到的数量
		g_nTotalView = 0;			// 已经查找了的数量
		CString strSearchStartPath(lpDlg->GetSearchLocation());
		short nSearchThreadIndex = 0;
		HANDLE hSearchThread[26] = { 0 };
		DWORD dwSeachThreadId[26] = { 0 };
		if (strSearchStartPath == _T("0"))
		{
			TCHAR szAllDriverLetters[100] = { 0 };
			DWORD len = GetLogicalDriveStrings(sizeof(szAllDriverLetters) / sizeof(TCHAR), szAllDriverLetters);
			for (TCHAR * lpszCurrentDriverLetter = szAllDriverLetters; *lpszCurrentDriverLetter; lpszCurrentDriverLetter += _tcslen(lpszCurrentDriverLetter) + 1)
			{
				// 创建搜索线程
				Sleep(nSearchThreadIndex * 1000);
				StringCchPrintf(spi[nSearchThreadIndex].m_szStartLocation, MAX_PATH - 1, _T("%C:"), lpszCurrentDriverLetter[0]);
				spi[nSearchThreadIndex].m_bFastMode = lpDlg->GetFastMode();
				hSearchThread[nSearchThreadIndex] = CreateThread(
					NULL,         // 使用默认的安全描述符
					0,            // 使用默认的栈大小
					(LPTHREAD_START_ROUTINE)SearchThreadProc,
					(LPVOID)(spi + nSearchThreadIndex),
					CREATE_SUSPENDED,						// 先挂起
					dwSeachThreadId + nSearchThreadIndex);	// 取得线程ID
				if (hSearchThread[nSearchThreadIndex])
				{
					if (spi[nSearchThreadIndex].m_bFastMode)
						if (!SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_TIME_CRITICAL))
							if (!SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_HIGHEST))
								if (!SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_ABOVE_NORMAL))
									if (!SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_HIGHEST))
										SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_NORMAL);
					ResumeThread(hSearchThread[nSearchThreadIndex]);
					SetThreadPriorityBoost(hSearchThread[nSearchThreadIndex], !spi[nSearchThreadIndex].m_bFastMode);	// 系统动态调整线程优先级选项
					nSearchThreadIndex++;
				}
			}
			WaitForMultipleObjects(nSearchThreadIndex, hSearchThread, TRUE, INFINITE);
			for (short i = 0; i < nSearchThreadIndex; i++)
			{
				if (hSearchThread[i])
					CloseHandle(hSearchThread[i]);
			}
		}
		else
		{
			// 创建搜索线程
			DWORD ThreadID = 0;
			StringCchPrintf(spi[0].m_szStartLocation, MAX_PATH - 1, _T("%s"), strSearchStartPath);
			spi[0].m_bFastMode = lpDlg->GetFastMode();
			hSearchThread[0] = CreateThread(
				NULL,         // 使用默认的安全描述符
				0,            // 使用默认的栈大小
				(LPTHREAD_START_ROUTINE)SearchThreadProc,
				(LPVOID)&spi[0],
				CREATE_SUSPENDED,						// 先挂起
				&ThreadID);	// 取得线程ID
			if (hSearchThread)
			{
				if (spi[0].m_bFastMode)
					if (!SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_TIME_CRITICAL))
						if (!SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_HIGHEST))
							if (!SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_ABOVE_NORMAL))
								if (!SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_HIGHEST))
									SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_NORMAL);
				ResumeThread(hSearchThread[nSearchThreadIndex]);
				SetThreadPriorityBoost(hSearchThread[nSearchThreadIndex], !spi[nSearchThreadIndex].m_bFastMode);	// 系统动态调整线程优先级选项

				WaitForSingleObject(hSearchThread[nSearchThreadIndex], INFINITE);
				CloseHandle(hSearchThread[nSearchThreadIndex]);
				nSearchThreadIndex++;
			}
		}
		if (g_vecCurrentFindData.size())
		{
			lpDlg->InitList();
			lpDlg->NotifyStatusMsg(_T("正在更新搜索结果列表,请稍候..."));
			lpDlg->UpdateList(g_vecCurrentFindData);
			ULONG nViewCount = 0, nFoundCount = 0;
			for (short i = 0; i < nSearchThreadIndex; i++)
			{
				nViewCount += spi[i].m_nViewCount;
				nFoundCount += spi[i].m_nFoundCount;
			}
			StringCchPrintf(szMsg, nMSG_SIZE - 1, _T("搜索完成,在%d个项目中共找到了%d个对象。"), nViewCount, nFoundCount);
			lpDlg->NotifyStatusMsg(szMsg);
		}
		else
		{
			lpDlg->NotifyStatusMsg(_T("未找到!"));
		}

		// 搜索完了,重置状态
		g_vecCurrentFindData.clear();
		std::vector<FIND_DATA> vecCurrentFindDataTemp;
		g_vecCurrentFindData.swap(vecCurrentFindDataTemp);
		g_hBrokenEvent ? ResetEvent(g_hBrokenEvent) : 0;
		g_hSearchEvent ? ResetEvent(g_hSearchEvent) : 0;

		if (WaitForSingleObject(g_hQuitEvent, 50) == WAIT_OBJECT_0)
		{
			// 搜索任务完成之后检测有无退出信号
			OutputDebugString(_T("Quiting..."));
			break;
		}
	}

	return 0;
}
Exemplo n.º 15
0
int main(int argc, char *argv[])
{
#ifndef PRT_PLAT_WINUSER
    init_ros("test_motion_planner", &argc, argv);
#endif
    if (!ParseCommandLine(argc, argv))
    {
        PrintUsage();
        return 1;
    }

    const char* motion_planner_delta_s = getenv("MOTION_PLANNER_DELTA");
    if(motion_planner_delta_s) {
        Delta = atoi(motion_planner_delta_s);
        printf("Using MOTION_PLANNER_DELTA = %d\n", Delta);
    }

    printf("Press any key to start simulation\n");
    getchar();

	PRT_DBG_START_MEM_BALANCED_REGION
	{
		PRT_PROCESS *process;
		PRT_GUID processGuid;
		PRT_VALUE *payload;

		//Initialize the workspace
		WORKSPACE_INFO = ParseWorkspaceConfig(workspaceConfig);

#ifdef USE_DIJKSTRA_PRECOMPUTATION
        WS_LocationsList ends;
        ends.size = WORKSPACE_INFO->starts.size + WORKSPACE_INFO->ends.size;
        ends.locations = malloc(sizeof(WS_Coord) * ends.size);
        int count = 0;
        for(int i=0; i < WORKSPACE_INFO->starts.size; i++) {
            ends.locations[count++] = WORKSPACE_INFO->starts.locations[i];
        }
        for(int i=0; i < WORKSPACE_INFO->ends.size; i++) {
            ends.locations[count++] = WORKSPACE_INFO->ends.locations[i];
        }
        PreComputeObstacleDistanceH(WORKSPACE_INFO->dimension, WORKSPACE_INFO->obstacles, ends);
#endif

		processGuid.data1 = 1;
		processGuid.data2 = 0;
		processGuid.data3 = 0;
		processGuid.data4 = 0;
		process = PrtStartProcess(processGuid, &P_GEND_PROGRAM, ErrorHandler, Log);
        if (cooperative)
        {
            PrtSetSchedulingPolicy(process, PRT_SCHEDULINGPOLICY_COOPERATIVE);
        }
		if (parg == NULL)
		{
			payload = PrtMkNullValue();
		}
		else
		{
			int i = atoi(parg);
			payload = PrtMkIntValue(i);
		}

		PrtUpdateAssertFn(MyAssert);

		PrtMkMachine(process, P_MACHINE_Main, payload);

        if (cooperative)
        {
            // test some multithreading across state machines.
#if defined(PRT_PLAT_WINUSER)
			HANDLE* threadsArr = (HANDLE*)PrtMalloc(threads*sizeof(HANDLE));
            for (int i = 0; i < threads; i++)
            {
                DWORD threadId;
                threadsArr[i] = CreateThread(NULL, 16000, (LPTHREAD_START_ROUTINE)RunToIdle, process, 0, &threadId);
            }
			WaitForMultipleObjects(threads, threadsArr, TRUE, INFINITE);
			PrtFree(threadsArr);
#elif defined(PRT_PLAT_LINUXUSER)
typedef void *(*start_routine) (void *);
            pthread_t tid[threads];
            for (int i = 0; i < threads; i++)
            {
                pthread_create(&tid[i], NULL, (start_routine)RunToIdle, (void*)process);
            }
            for (int i = 0; i < threads; i++)
            {
                pthread_join(tid[i], NULL);
            }
#else
#error Invalid Platform
#endif
        }
		PrtFreeValue(payload);
		PrtStopProcess(process);
	}
	PRT_DBG_END_MEM_BALANCED_REGION

	//_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);
	//_CrtDumpMemoryLeaks();
}
Exemplo n.º 16
0
int wmain( int argc, wchar_t **argv, wchar_t **envp )
{
    std::wcout << "named pipe server" << std::endl;

    HANDLE h_wait_stop = CreateEvent( nullptr, 0, 0, nullptr );

    // We need to use overlapped IO for this, so we dont block when
    // waiting for a client to connect.  This is the only effective way
    // to handle either a client connection, or a service stop request.
    OVERLAPPED overlapped;
    overlapped.Internal = 0;
    overlapped.InternalHigh = 0;
    overlapped.Pointer = 0;

    std::wcout << "sizeof( overlapperd ) " << sizeof( overlapped ) << std::endl;
    std::wcout << "sizeof( overlapperd.Internal ) " << sizeof( overlapped.Internal ) << std::endl;
    std::wcout << "sizeof( overlapperd.InternalHigh ) " << sizeof( overlapped.InternalHigh ) << std::endl;
    std::wcout << "sizeof( overlapperd.Pointer ) " << sizeof( overlapped.Pointer ) << std::endl;
    std::wcout << "sizeof( overlapperd.hEvent ) " << sizeof( overlapped.hEvent ) << std::endl;

    // And create an event to be used in the OVERLAPPED object.
    overlapped.hEvent = CreateEventW( nullptr, 0, 0, nullptr );

    // We create our named pipe.
    char *pipe_name = "\\\\.\\pipe\\Barry's Emacs 8.2";

    HANDLE h_pipe = CreateNamedPipeA(
                    pipe_name,                      //  __in      LPCTSTR lpName,
                    PIPE_ACCESS_DUPLEX
                    | FILE_FLAG_OVERLAPPED,         //  __in      DWORD dwOpenMode,
                    PIPE_TYPE_MESSAGE
                    | PIPE_READMODE_MESSAGE
                    | PIPE_REJECT_REMOTE_CLIENTS,   //  __in      DWORD dwPipeMode,
                    PIPE_UNLIMITED_INSTANCES,       //  __in      DWORD nMaxInstances,
                    0,                              //  __in      DWORD nOutBufferSize,
                    0,                              //  __in      DWORD nInBufferSize,
                    100,                            //  __in      DWORD nDefaultTimeOut, (100ms)
                    nullptr                            //  __in_opt  LPSECURITY_ATTRIBUTES lpSecurityAttributes
                    );
    if( h_pipe == 0 )
    {
        std::wcerr << "Failed to CreateNamedPipeA: " << __getLastErrorMessage().c_str() << std::endl;
        return 1;
    }

    // Loop accepting and processing connections
    for(;;)
    {
        std::wcout << "__windowsCommandLineHandler loop top" << std::endl;

        DWORD hr = ConnectNamedPipe( h_pipe, &overlapped );
        if( hr == ERROR_PIPE_CONNECTED )
        {
            // Client is fast, and already connected - signal event
            SetEvent( overlapped.hEvent );
        }

        std::wcout << "__windowsCommandLineHandler connected to named pipe" << std::endl;

        // Wait for either a connection, or a service stop request.
        HANDLE wait_handles[2];
        wait_handles[0] = h_wait_stop;
        wait_handles[1] = overlapped.hEvent;

        std::wcout << "__windowsCommandLineHandler WaitForMultipleObjects..." << std::endl;
        DWORD rc = WaitForMultipleObjects( 2, wait_handles, 0, INFINITE );

        if( rc == WAIT_OBJECT_0 )
        {
            std::wcout << "__windowsCommandLineHandler Stop event" << std::endl;
            // Stop event
            break;
        }
        else
        {
            std::wcout << "__windowsCommandLineHandler data ready for read" << std::endl;

            // Pipe event - read the data, and write it back.
            char buf_client[32768];
            DWORD buf_size( sizeof( buf_client )-1 );
            hr = ReadFile( h_pipe, buf_client, buf_size, &buf_size, nullptr );
            if( !hr )
            {
                std::wcout << "ReadFile failed: " << __getLastErrorMessage().c_str() << std::endl;
            }
            else
            {
                buf_client[ buf_size ] = 0;
                std::wcout << "__windowsCommandLineHandler read command size " << buf_size << " \"" << buf_client << "\"" << std::endl;

                if( buf_size > 0 )
                {
                    char *reply = "Reply";
                    DWORD reply_size = strlen( reply );

                    hr = WriteFile( h_pipe, reply, reply_size, &reply_size, nullptr );
                    if( !hr )
                    {
                        std::wcout << "WriteFile failed: " << __getLastErrorMessage().c_str() << std::endl;
                    }
                }
            }
            // And disconnect from the client.
            DisconnectNamedPipe( h_pipe );
            std::wcout << "__windowsCommandLineHandler Disconnected named pipe" << std::endl;
        }
    }
    return 0;
}
Exemplo n.º 17
0
//This method gets called by its static counterpart, and is the actual thread logic
DWORD WINAPI Kinect::ProcessThread()
{
	//numEvents is the number of events, handleEvents is an Array of all the events being handled.
	const int numEvents = 4;
	HANDLE handleEvents[numEvents] = { treadNuiProcessStop, nextColorFrameEvent, nextDepthFrameEvent, nextSkeletonEvent };
	std::stringstream ss;
	int eventIdx, colorFrameFPS = 0, depthFrameFPS = 0;
	DWORD t, lastColorFPSTime, lastDepthFPSTime;
	CString TextFPS;


	// Initializes the static text fields for FPS text.
	CStatic * MFC_ecFPSCOLOR, * MFC_ecFPSDEPTH;
	//Initialize the Image vieuwer on the GUI. Because this class does not inherit anything relatied to MFC, we need CWnd::GetDlgItem instead of just GetDlgItem.
	// (By the way: because the main is a CWnd and 'GetDlgItem()' means the same thing as 'this->GetDlgItem()', main.cpp actually uses the same method.)
	MFC_ecFPSCOLOR = (CStatic *) cWnd.GetDlgItem(1013);
	MFC_ecFPSDEPTH = (CStatic *) cWnd.GetDlgItem(1014);	

	lastColorFPSTime	= timeGetTime( );
	lastDepthFPSTime	= timeGetTime( );

	//blank the skeleton display when started.
	lastSkeletonFoundTime = 0;

	bool continueProcess = true;
	while ( continueProcess )
	{
		// wait for any of the events
		eventIdx = WaitForMultipleObjects( numEvents, handleEvents, FALSE, 100);

		// timed out, continue
		if ( eventIdx == WAIT_TIMEOUT)
		{
			continue;
		}

		// stop event was signalled
		if ( WAIT_OBJECT_0 == eventIdx )
		{
			continueProcess = false;
			break;
		}

		// Wait for each object individually with a 0 timeout to make sure to
		// process all signalled objects if multiple objects were signalled
		// this loop iteration

		// In situations where perfect correspondance between color/depth/skeleton
		// is essential, a priority queue should be used to service the item
		// which has been updated the longest ago Copyright Microsoft.


		if ( WAIT_OBJECT_0 == WaitForSingleObject( nextColorFrameEvent, 0) )
		{
			if( gotColorAlert() )
			{
				++colorFrameFPS; 
			}
		}

		if ( WAIT_OBJECT_0 == WaitForSingleObject( nextDepthFrameEvent, 0) )
		{
			if( gotDepthAlert() )
			{
				++depthFrameFPS;
			}
		}

		if (WAIT_OBJECT_0 == WaitForSingleObject( nextSkeletonEvent, 0))
		{
			if (gotSkeletonAlert() )
			{
			}
		}


		// fps counter for the color stream.
		// compare first frametime with the current time, if more then 1000 passed,
		// one second passed.
		t = timeGetTime();
		if((t - lastColorFPSTime) > 1000)
		{
			ss<<colorFrameFPS;
			TextFPS= ss.str().c_str();
			MFC_ecFPSCOLOR->SetWindowText(TextFPS);
			colorFrameFPS = 0;
			lastColorFPSTime = timeGetTime();

			// Reset both the CString text and the stringstream, so you don't get any crazy value's.
			TextFPS.Empty();
			ss.str("");

			ss<<depthFrameFPS;
			TextFPS = ss.str().c_str();
			MFC_ecFPSDEPTH->SetWindowText(TextFPS);
			depthFrameFPS = 0;

			// Reset both the CString text and the stringstream, so you don't get any crazy value's.
			TextFPS.Empty();
			ss.str("");

			if( (t - lastSkeletonFoundTime) > 300)
			{
				if (!screenBlanked)
				{
					blankSkeletonScreen();
					screenBlanked = true;
				}
			}
		}
	}
	return 0;
}
Exemplo n.º 18
0
int _tmain(int argc, _TCHAR* argv[])
{
    WSADATA wsaData;
    int result;

    system("pause");

    result = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if(0 != result)
    {
        _tprintf(_T("WSAStartup error, code: %d"), WSAGetLastError());
        exit(0);
    }

    SOCKET socketForProbe = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(INVALID_SOCKET == socketForProbe)
    {
        _tprintf(_T("socket error, code: %d"), WSAGetLastError());
        exit(0);
    }

    sockaddr_in sockaddrClient;
    memset(&sockaddrClient, 0x0, sizeof(sockaddr_in));
    sockaddrClient.sin_addr.s_addr = htonl(INADDR_ANY);
    sockaddrClient.sin_family = AF_INET;
    sockaddrClient.sin_port = htons(0);

    sockaddr_in sockaddrMulticastAddrForOnvif;
    memset(&sockaddrMulticastAddrForOnvif, 0x0, sizeof(sockaddr_in));
    InetPton(AF_INET, _T("239.255.255.250"), &sockaddrMulticastAddrForOnvif.sin_addr.s_addr);
    sockaddrMulticastAddrForOnvif.sin_family = AF_INET;
    sockaddrMulticastAddrForOnvif.sin_port = htons(3702);

    result = bind(socketForProbe, (struct sockaddr*)&sockaddrClient, sizeof(sockaddr_in));
    if(0 != result)
    {
        _tprintf(_T("bind error, code: %d"), WSAGetLastError());
        exit(0);
    }

    DWORD timeOut = 5000;

    result = setsockopt(socketForProbe, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeOut, sizeof(DWORD));
    if(0 != result)
    {
        _tprintf(_T("setsockopt error, code: %d"), WSAGetLastError());
        exit(0);
    }


    char* pProbeMessage = (char*)malloc(2048);
    if(NULL == pProbeMessage)
    {
        _tprintf(_T("malloc error"));
        exit(0);
    }

    receiveThreadParameter parameter;
    BOOL loop = TRUE;
    DWORD threadID;
    parameter.socketForProbe = &socketForProbe;
    parameter.bLoop = &loop;

    UUID uuid;
    RPC_STATUS rpcStatus = UuidCreate(&uuid);
    if(RPC_S_OK != rpcStatus)
    {
        _tprintf(_T("UuidCreate error, code: %d"), WSAGetLastError());
        exit(0);
    }

    RPC_CSTR RpcCstr;
    rpcStatus = UuidToStringA(&uuid, &RpcCstr);
    if(RPC_S_OK != rpcStatus)
    {
        _tprintf(_T("UuidCreate error, code: %d"), WSAGetLastError());
        exit(0);
    }

    result = _snprintf_s(pProbeMessage, 2048, _TRUNCATE, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:SOAP-ENC=\"http://www.w3.org/2003/05/soap-encoding\" xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:wsdd=\"http://schemas.xmlsoap.org/ws/2005/04/discovery\"><SOAP-ENV:Header><wsa:MessageID>urn:uuid:%s</wsa:MessageID><wsa:To SOAP-ENV:mustUnderstand=\"true\">urn:schemas-xmlsoap-org:ws:2005:04:discovery</wsa:To><wsa:Action SOAP-ENV:mustUnderstand=\"true\">http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe</wsa:Action></SOAP-ENV:Header><SOAP-ENV:Body><wsdd:Probe></wsdd:Probe></SOAP-ENV:Body></SOAP-ENV:Envelope>", RpcCstr);
    if(-1 == result)
    {
        _tprintf(_T("_snprintf_s error"));
        exit(0);
    }

    rpcStatus = RpcStringFreeA(&RpcCstr);
    if(RPC_S_OK != rpcStatus)
    {
        _tprintf(_T("UuidCreate error, code: %d"), WSAGetLastError());
        exit(0);
    }

    //result = _snprintf_s(pProbeMessage, 2048, _TRUNCATE, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:SOAP-ENC=\"http://www.w3.org/2003/05/soap-encoding\" xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:wsdd=\"http://schemas.xmlsoap.org/ws/2005/04/discovery\"><SOAP-ENV:Header><wsa:MessageID>urn:uuid:bc9fb550-1dd1-11b2-807c-c056e3fb5481</wsa:MessageID><wsa:To SOAP-ENV:mustUnderstand=\"true\">urn:schemas-xmlsoap-org:ws:2005:04:discovery</wsa:To><wsa:Action SOAP-ENV:mustUnderstand=\"true\">http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe</wsa:Action></SOAP-ENV:Header><SOAP-ENV:Body><wsdd:Probe><wsdd:Types>Device</wsdd:Types><wsdd:Scopes></wsdd:Scopes></wsdd:Probe></SOAP-ENV:Body></SOAP-ENV:Envelope>");
    //if(-1 == result)
    //{
    //    _tprintf(_T("_snprintf_s error"));
    //    exit(0);
    //}

    HANDLE hThread = CreateThread(NULL, 0, receiveThread, &parameter, 0, &threadID);
    if(NULL == hThread)
    {
        _tprintf(_T("CreateThread error, code: %d"), GetLastError());
        exit(0);
    }

    result = sendto(socketForProbe, pProbeMessage, result, 0, (sockaddr*)&sockaddrMulticastAddrForOnvif, sizeof(sockaddr_in));
    if(SOCKET_ERROR == result)
    {
        _tprintf(_T("sendto error, code: %d"), WSAGetLastError());
        exit(0);
    }


    Sleep(5000);

    loop = FALSE;

    WaitForMultipleObjects(1, &hThread, TRUE, INFINITE);

    CloseHandle(hThread);

    free(pProbeMessage);
    pProbeMessage = NULL;

    result = closesocket(socketForProbe);
    if(0 != result)
    {
        _tprintf(_T("closesocket error, code: %d"), WSAGetLastError());
        exit(0);
    }

    result = WSACleanup();
    if(0 != result)
    {
        _tprintf(_T("WSACleanup error, code: %d"), WSAGetLastError());
        exit(0);
    }

    system("pause");

    return 0;
}
Exemplo n.º 19
0
int DcmFileProcess::readAllDcm(const char* FilePath, std::vector<float>& position)
{
	//构造类对象  
	CStatDir statdir;
	std::vector<std::string> AllDcmFile;

	position.clear();
	float min_axial = 1000.0f;
	float max_axial = -1000.0f;
	float init_x = 0.0f;
	float init_y = 0.0f;
	float pixelspacing = 0.0f;

	int count = 0;
	//设置要遍历的目录  
	if (!statdir.SetInitDir(FilePath))
	{
		puts("目录不存在");
	}
	//开始遍历,获取该文件夹下所有dcm格式图像,一般为一个病患
	AllDcmFile.clear();
	AllDcmFile = statdir.BeginBrowseFilenames("*.dcm");
	//创建缓冲文件夹
	createCache();
	std::string dirName = GetExePath();
	dirName += "\\cache\\";

	cv::Mat mat[710];

	// 获取原始dcm图像的前缀目录
	std::string subImageName = dirName;
	// 获取原始dcm图像的前缀目录的string转换为char*
	const char *chSubImageName = subImageName.c_str();

	for (auto iter = AllDcmFile.cbegin(); iter != AllDcmFile.cend(); iter++)
	{
		// 将原始dcm图像的string转换为char*
		const char *chImageName = (*iter).c_str();
		// 基于dcmtk实现类
		THU_STD_NAMESPACE::TDcmFileFormat dcm = THU_STD_NAMESPACE::TDcmFileFormat(chImageName);

		std::string result = dcm.getImagePositionPatient();
		std::vector<std::string> ImagePosition;
		split(result, "\\", ImagePosition);
		float axial = (float)atof(ImagePosition[2].c_str());
		if (axial > max_axial) max_axial = axial;
		if (axial < min_axial) min_axial = axial;
		// 得到世界坐标的初始值
		if (count < 1)
		{
			init_x = (float)atof(ImagePosition[0].c_str());
			init_y = (float)atof(ImagePosition[1].c_str());

			// 获取dcm图像的PixelSpacing
			std::string space = dcm.getPixelSpacing();
			std::vector<std::string> PixelSpacing;
			split(space, "\\", PixelSpacing);
			pixelspacing = (float)atof(PixelSpacing[0].c_str());
		}
		
		// 获取dcm图像的InstanceNumber
		int InstancePosition = dcm.getPositionNumber();
		// 生成bmp图像存储路径
		char BmpName[256];
		sprintf_s(BmpName, "%s%06d.bmp", chSubImageName, InstancePosition);
		// 进行图像转换
		dcm.setWindow(715, 3478);
		dcm.saveToBmp(BmpName);
		//读取所有dcm图像构造三维数组
		cv::Mat temp = cv::imread(BmpName, cv::IMREAD_GRAYSCALE);
		mat[InstancePosition - 1] = temp;

		count++;
	}

	position.push_back(max_axial);
	position.push_back(min_axial);
	position.push_back((max_axial - min_axial) / count);
	position.push_back(init_x);
	position.push_back(init_y);
	position.push_back(pixelspacing);

	//多线程需要处理的线程数,分别对应矢状位与冠状位
	const int THREAD_NUM = 2;
	HANDLE handle[THREAD_NUM];
	//构造子线程参数结构体
	ThreadInfo threadInfo;
	threadInfo.dirName = dirName;
	threadInfo.count = count;
	for (int i = 0; i < count; i++)
		threadInfo.mat[i] = mat[i];
	//Coronal子线程
	handle[0] = (HANDLE)_beginthreadex(NULL, 0, ThreadCoronal, &threadInfo, 0, NULL);
	//Sigattal子线程
	handle[1] = (HANDLE)_beginthreadex(NULL, 0, ThreadSagittal, &threadInfo, 0, NULL);
	WaitForMultipleObjects(THREAD_NUM, handle, TRUE, INFINITE);

	return count;
}
Exemplo n.º 20
0
/***************************************************************************
 * 				MCIAVI_player			[internal]
 */
static	DWORD	MCIAVI_player(WINE_MCIAVI *wma, DWORD dwFlags, LPMCI_PLAY_PARMS lpParms)
{
    DWORD		dwRet;
    LPWAVEHDR		waveHdr = NULL;
    unsigned		i, nHdr = 0;
    DWORD		numEvents = 1;
    HANDLE		events[2];
    double next_frame_us;

    EnterCriticalSection(&wma->cs);

    if (wma->dwToVideoFrame <= wma->dwCurrVideoFrame)
    {
        dwRet = 0;
        goto mci_play_done;
    }

    events[0] = wma->hStopEvent;
    if (wma->lpWaveFormat) {
       if (MCIAVI_OpenAudio(wma, &nHdr, &waveHdr) != 0)
        {
            /* can't play audio */
            HeapFree(GetProcessHeap(), 0, wma->lpWaveFormat);
            wma->lpWaveFormat = NULL;
        }
       else
       {
            /* fill the queue with as many wave headers as possible */
            MCIAVI_PlayAudioBlocks(wma, nHdr, waveHdr);
            events[1] = wma->hEvent;
            numEvents = 2;
       }
    }

    next_frame_us = currenttime_us();
    while (wma->dwStatus == MCI_MODE_PLAY)
    {
        HDC hDC;
        double tc, delta;
        DWORD ret;

        tc = currenttime_us();

        hDC = wma->hWndPaint ? GetDC(wma->hWndPaint) : 0;
        if (hDC)
        {
            while(next_frame_us <= tc && wma->dwCurrVideoFrame < wma->dwToVideoFrame){
                double dur;
                ++wma->dwCurrVideoFrame;
                dur = MCIAVI_PaintFrame(wma, hDC);
                if(!dur)
                    break;
                next_frame_us += dur;
                TRACE("next_frame: %f\n", next_frame_us);
            }
            ReleaseDC(wma->hWndPaint, hDC);
        }
        if(wma->dwCurrVideoFrame >= wma->dwToVideoFrame)
            break;

        if (wma->lpWaveFormat)
            MCIAVI_PlayAudioBlocks(wma, nHdr, waveHdr);

        tc = currenttime_us();
        if(tc < next_frame_us)
            delta = next_frame_us - tc;
        else
            delta = 0;

        LeaveCriticalSection(&wma->cs);
        ret = WaitForMultipleObjects(numEvents, events, FALSE, delta / 1000);
        EnterCriticalSection(&wma->cs);
        if (ret == WAIT_OBJECT_0 || wma->dwStatus != MCI_MODE_PLAY) break;
    }

    if (wma->lpWaveFormat) {
       while (wma->dwEventCount != nHdr - 1)
        {
            LeaveCriticalSection(&wma->cs);
            Sleep(100);
            EnterCriticalSection(&wma->cs);
        }

	/* just to get rid of some race conditions between play, stop and pause */
	LeaveCriticalSection(&wma->cs);
	waveOutReset(wma->hWave);
	EnterCriticalSection(&wma->cs);

	for (i = 0; i < nHdr; i++)
	    waveOutUnprepareHeader(wma->hWave, &waveHdr[i], sizeof(WAVEHDR));
    }

    dwRet = 0;

    if (wma->lpWaveFormat) {
	HeapFree(GetProcessHeap(), 0, waveHdr);

	if (wma->hWave) {
	    LeaveCriticalSection(&wma->cs);
	    waveOutClose(wma->hWave);
	    EnterCriticalSection(&wma->cs);
	    wma->hWave = 0;
	}
	CloseHandle(wma->hEvent);
    }

mci_play_done:
    wma->dwStatus = MCI_MODE_STOP;

    if (dwFlags & MCI_NOTIFY) {
	TRACE("MCI_NOTIFY_SUCCESSFUL %08lX !\n", lpParms->dwCallback);
	mciDriverNotify(HWND_32(LOWORD(lpParms->dwCallback)),
                       wma->wDevID, MCI_NOTIFY_SUCCESSFUL);
    }
    LeaveCriticalSection(&wma->cs);
    return dwRet;
}
Exemplo n.º 21
0
int
WaitLatchOrSocket(volatile Latch *latch, SOCKET sock, long timeout)
{
	DWORD		rc;
	HANDLE		events[3];
	HANDLE		latchevent;
	HANDLE		sockevent;
	int			numevents;
	int			result = 0;

	latchevent = latch->event;

	events[0] = latchevent;
	events[1] = pgwin32_signal_event;
	numevents = 2;
	if (sock != PGINVALID_SOCKET)
	{
		sockevent = WSACreateEvent();
		WSAEventSelect(sock, sockevent, FD_READ);
		events[numevents++] = sockevent;
	}

	for (;;)
	{
		/*
		 * Reset the event, and check if the latch is set already. If someone
		 * sets the latch between this and the WaitForMultipleObjects() call
		 * below, the setter will set the event and WaitForMultipleObjects()
		 * will return immediately.
		 */
		if (!ResetEvent(latchevent))
			elog(ERROR, "ResetEvent failed: error code %d", (int) GetLastError());
		if (latch->is_set)
		{
			result = 1;
			break;
		}

		rc = WaitForMultipleObjects(numevents, events, FALSE,
								(timeout >= 0) ? (timeout / 1000) : INFINITE);
		if (rc == WAIT_FAILED)
			elog(ERROR, "WaitForMultipleObjects() failed: error code %d", (int) GetLastError());
		else if (rc == WAIT_TIMEOUT)
		{
			result = 0;
			break;
		}
		else if (rc == WAIT_OBJECT_0 + 1)
			pgwin32_dispatch_queued_signals();
		else if (rc == WAIT_OBJECT_0 + 2)
		{
			Assert(sock != PGINVALID_SOCKET);
			result = 2;
			break;
		}
		else if (rc != WAIT_OBJECT_0)
			elog(ERROR, "unexpected return code from WaitForMultipleObjects(): %d", rc);
	}

	/* Clean up the handle we created for the socket */
		if (sock != PGINVALID_SOCKET)
	{
		WSAEventSelect(sock, sockevent, 0);
		WSACloseEvent(sockevent);
	}

	return result;
}
Exemplo n.º 22
0
DWORD WINAPI Cadthread(LPVOID lpParam)
{
	HDESK inputdesktop = OpenInputDesktop(0, FALSE,
				DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |
				DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL |
				DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
				DESKTOP_SWITCHDESKTOP | GENERIC_WRITE);
		SetThreadDesktop(inputdesktop);
		DWORD yerror= GetLastError();

		comm_serv keyEventFn;
		comm_serv StopeventFn;
		comm_serv StarteventFn;
		if (!keyEventFn.Init("keyEvent",sizeof(keyEventdata),0,false,false)) goto error;
		if (!StopeventFn.Init("stop_event",0,0,false,false)) goto error;
		if (!StarteventFn.Init("start_event",1,1,false,false)) goto error;
		HANDLE Events_ini[1];
		Events_ini[0]=StarteventFn.GetEvent();
		DWORD dwEvent = WaitForMultipleObjects(1,Events_ini,FALSE,1000);
		switch(dwEvent)
				{
					case WAIT_OBJECT_0 + 0:
						unsigned char in;
						StarteventFn.ReadData((char*)&in);
						StarteventFn.SetData((char*) &in);
						break;
					case WAIT_TIMEOUT:
						 goto error;
						 break;
				}

		HANDLE Events[3];
		Events[0]=keyEventFn.GetEvent();
		Events[1]=StopeventFn.GetEvent();
		Events[2]=StarteventFn.GetEvent();
		int counter=0;
		while (true)
		{
		DWORD dwEvent = WaitForMultipleObjects(3,Events,FALSE,1000);
		switch(dwEvent)
				{
					case WAIT_OBJECT_0 + 0: 
						keyEventdata ked;
						keyEventFn.ReadData((char*)&ked);
						keybd_event(ked.bVk,    ked.bScan,ked.dwflags,0);
						keyEventFn.SetData(NULL);
						break;
					case WAIT_OBJECT_0 + 1: 
						goto error;
						break;
					case WAIT_OBJECT_0 + 2: 						
						unsigned char in;
						StarteventFn.ReadData((char*)&in);
						StarteventFn.SetData((char*) &in);
						InputDesktopSelected();
						counter=0;
						break;
					case WAIT_TIMEOUT:						
						counter++;
						break;
				}
		if (counter>3) break;
		}

error:
		return 0;
}
Exemplo n.º 23
0
DWORD WINAPI bs_thread(LPVOID tid_ptr){
#else
int bs_thread(void *tid_ptr) {
#endif
    int i, j;
    fptype price;
    fptype priceDelta;
    int tid = *(int *)tid_ptr;
    int start = tid * (numOptions / nThreads);
    int end = start + (numOptions / nThreads);

    for (j=0; j<NUM_RUNS; j++) {
#ifdef ENABLE_OPENMP
#pragma omp parallel for
        for (i=0; i<numOptions; i++) {
#else  //ENABLE_OPENMP
        for (i=start; i<end; i++) {
#endif //ENABLE_OPENMP
            /* Calling main function to calculate option value based on 
             * Black & Sholes's equation.
             */
            price = BlkSchlsEqEuroNoDiv( sptprice[i], strike[i],
                                         rate[i], volatility[i], otime[i], 
                                         otype[i], 0);
            prices[i] = price;
            
#ifdef ERR_CHK   
            priceDelta = data[i].DGrefval - price;
            if( fabs(priceDelta) >= 1e-4 ){
                printf("Error on %d. Computed=%.5f, Ref=%.5f, Delta=%.5f\n",
                       i, price, data[i].DGrefval, priceDelta);
                numError ++;
            }
#endif
        }
    }

    return 0;
}

int main (int argc, char **argv)
{
    FILE *file;
    int i;
    int loopnum;
    fptype * buffer;
    int * buffer2;
    int rv;

#ifdef PARSEC_VERSION
#define __PARSEC_STRING(x) #x
#define __PARSEC_XSTRING(x) __PARSEC_STRING(x)
        printf("PARSEC Benchmark Suite Version "__PARSEC_XSTRING(PARSEC_VERSION)"\n");
	fflush(NULL);
#else
        printf("PARSEC Benchmark Suite\n");
	fflush(NULL);
#endif //PARSEC_VERSION
#ifdef ENABLE_PARSEC_HOOKS
   __parsec_bench_begin(__parsec_blackscholes);
#endif

   if (argc != 4)
        {
                printf("Usage:\n\t%s <nthreads> <inputFile> <outputFile>\n", argv[0]);
                exit(1);
        }
    nThreads = atoi(argv[1]);
    char *inputFile = argv[2];
    char *outputFile = argv[3];

    //Read input data from file
    file = fopen(inputFile, "r");
    if(file == NULL) {
      printf("ERROR: Unable to open file %s.\n", inputFile);
      exit(1);
    }
    rv = fscanf(file, "%i", &numOptions);
    if(rv != 1) {
      printf("ERROR: Unable to read from file %s.\n", inputFile);
      fclose(file);
      exit(1);
    }
    if(nThreads > numOptions) {
      printf("WARNING: Not enough work, reducing number of threads to match number of options.\n");
      nThreads = numOptions;
    }

#if !defined(ENABLE_THREADS) && !defined(ENABLE_OPENMP)
    if(nThreads != 1) {
        printf("Error: <nthreads> must be 1 (serial version)\n");
        exit(1);
    }
#endif

    // alloc spaces for the option data
    data = (OptionData*)malloc(numOptions*sizeof(OptionData));
    prices = (fptype*)malloc(numOptions*sizeof(fptype));
    for ( loopnum = 0; loopnum < numOptions; ++ loopnum )
    {
        rv = fscanf(file, "%f %f %f %f %f %f %c %f %f", &data[loopnum].s, &data[loopnum].strike, &data[loopnum].r, &data[loopnum].divq, &data[loopnum].v, &data[loopnum].t, &data[loopnum].OptionType, &data[loopnum].divs, &data[loopnum].DGrefval);
        if(rv != 9) {
          printf("ERROR: Unable to read from file %s with loopnum %d.\n", inputFile, loopnum);
          fclose(file);
          exit(1);
        }
    }
    rv = fclose(file);
    if(rv != 0) {
      printf("ERROR: Unable to close file %s.\n", inputFile);
      exit(1);
    }

#ifdef ENABLE_THREADS
    
//    pthread_mutexattr_init( &_M4_normalMutexAttr);
//    pthread_mutexattr_settype( &_M4_normalMutexAttr, PTHREAD_MUTEX_NORMAL);
    _M4_numThreads = nThreads;
    {
        int _M4_i;
        for ( _M4_i = 0; _M4_i < MAX_THREADS; _M4_i++) {
            _M4_threadsTable[_M4_i] = -1;
        }
    }
;
#endif
    printf("Num of Options: %d\n", numOptions);
    printf("Num of Runs: %d\n", NUM_RUNS);

#define PAD 256
#define LINESIZE 64

    buffer = (fptype *) malloc(5 * numOptions * sizeof(fptype) + PAD);
    sptprice = (fptype *) (((unsigned long long)buffer + PAD) & ~(LINESIZE - 1));
    strike = sptprice + numOptions;
    rate = strike + numOptions;
    volatility = rate + numOptions;
    otime = volatility + numOptions;

    buffer2 = (int *) malloc(numOptions * sizeof(fptype) + PAD);
    otype = (int *) (((unsigned long long)buffer2 + PAD) & ~(LINESIZE - 1));

    for (i=0; i<numOptions; i++) {
        otype[i]      = (data[i].OptionType == 'P') ? 1 : 0;
        sptprice[i]   = data[i].s;
        strike[i]     = data[i].strike;
        rate[i]       = data[i].r;
        volatility[i] = data[i].v;    
        otime[i]      = data[i].t;
    }

    printf("Size of data: %d\n", numOptions * (sizeof(OptionData) + sizeof(int)));

#ifdef ENABLE_PARSEC_HOOKS
    __parsec_roi_begin();
#endif
#ifdef ENABLE_THREADS
    int tids[nThreads];
	pthread_t thread_table[nThreads];
    for(i=0; i<nThreads; i++) {
        tids[i]=i;
    }
    for(i=0; i<nThreads; i++) { 
//		fprintf(stderr, "create %d thread\n", i);
		pthread_create(&thread_table[i],NULL,(void *(*)(void *))bs_thread,(void *)&tids[i]);
    }
    for(i=0; i<nThreads; i++) {
		pthread_join(thread_table[i], NULL);
	}
#else//ENABLE_THREADS
#ifdef ENABLE_OPENMP
    {
        int tid=0;
        omp_set_num_threads(nThreads);
        bs_thread(&tid);
    }
#else //ENABLE_OPENMP
#ifdef WIN32 
    if (nThreads > 1)
    {
        HANDLE threads[MAX_THREADS];
                int nums[MAX_THREADS];
                for(i=0; i<nThreads; i++) {
                        nums[i] = i;
                        threads[i] = CreateThread(0, 0, bs_thread, &nums[i], 0, 0);
                }
                WaitForMultipleObjects(nThreads, threads, TRUE, INFINITE);
    } else
#endif
    {
        int tid=0;
        bs_thread(&tid);
    }
#endif //ENABLE_OPENMP
#endif //ENABLE_THREADS
#ifdef ENABLE_PARSEC_HOOKS
    __parsec_roi_end();
#endif

    //Write prices to output file
    file = fopen(outputFile, "w");
    if(file == NULL) {
      printf("ERROR: Unable to open file %s.\n", outputFile);
      exit(1);
    }
    rv = fprintf(file, "%i\n", numOptions);
    if(rv < 0) {
      printf("ERROR: Unable to write to file %s.\n", outputFile);
      fclose(file);
      exit(1);
    }
    for(i=0; i<numOptions; i++) {
      rv = fprintf(file, "%.18f\n", prices[i]);
      if(rv < 0) {
        printf("ERROR: Unable to write to file %s.\n", outputFile);
        fclose(file);
        exit(1);
      }
    }
    rv = fclose(file);
    if(rv != 0) {
      printf("ERROR: Unable to close file %s.\n", outputFile);
      exit(1);
    }

#ifdef ERR_CHK
    printf("Num Errors: %d\n", numError);
#endif
    free(data);
    free(prices);

#ifdef ENABLE_PARSEC_HOOKS
    __parsec_bench_end();
#endif

    return 0;
}
Exemplo n.º 24
0
int _tmain(int argc, _TCHAR* argv[])
{
	cv::setUseOptimized( true );

	// Kinectのインスタンス生成、初期化
	INuiSensor* pSensor;
	HRESULT hResult = S_OK;
	hResult = NuiCreateSensorByIndex( 0, &pSensor );
	if( FAILED( hResult ) ){
		std::cerr << "Error : NuiCreateSensorByIndex" << std::endl;
		return -1;
	}

	hResult = pSensor->NuiInitialize( NUI_INITIALIZE_FLAG_USES_COLOR | NUI_INITIALIZE_FLAG_USES_DEPTH_AND_PLAYER_INDEX | NUI_INITIALIZE_FLAG_USES_SKELETON );
	if( FAILED( hResult ) ){
		std::cerr << "Error : NuiInitialize" << std::endl;
		return -1;
	}

	// Colorストリーム
	HANDLE hColorEvent = INVALID_HANDLE_VALUE;
	HANDLE hColorHandle = INVALID_HANDLE_VALUE;
	hColorEvent = CreateEvent( nullptr, true, false, nullptr );
	hResult = pSensor->NuiImageStreamOpen( NUI_IMAGE_TYPE_COLOR, NUI_IMAGE_RESOLUTION_640x480, 0, 2, hColorEvent, &hColorHandle );
	if( FAILED( hResult ) ){
		std::cerr << "Error : NuiImageStreamOpen( COLOR )" << std::endl;
		return -1;
	}

	// Depth&Playerストリーム
	HANDLE hDepthPlayerEvent = INVALID_HANDLE_VALUE;
	HANDLE hDepthPlayerHandle = INVALID_HANDLE_VALUE;
	hDepthPlayerEvent = CreateEvent( nullptr, true, false, nullptr );
	hResult = pSensor->NuiImageStreamOpen( NUI_IMAGE_TYPE_DEPTH_AND_PLAYER_INDEX, NUI_IMAGE_RESOLUTION_640x480, 0, 2, hDepthPlayerEvent, &hDepthPlayerHandle );
	if( FAILED( hResult ) ){
		std::cerr << "Error : NuiImageStreamOpen( DEPTH&PLAYER )" << std::endl;
		return -1;
	}

	// Skeletonストリーム
	HANDLE hSkeletonEvent = INVALID_HANDLE_VALUE;
	hSkeletonEvent = CreateEvent( nullptr, true, false, nullptr );
	hResult = pSensor->NuiSkeletonTrackingEnable( hSkeletonEvent, 0 );
	if( FAILED( hResult ) ){
		std::cerr << "Error : NuiSkeletonTrackingEnable" << std::endl;
		return -1;
	}

	HANDLE hEvents[3] = { hColorEvent, hDepthPlayerEvent, hSkeletonEvent };

	// カラーテーブル
	cv::Vec3b color[7];
	color[0] = cv::Vec3b(   0,   0,   0 );
	color[1] = cv::Vec3b( 255,   0,   0 );
	color[2] = cv::Vec3b(   0, 255,   0 );
	color[3] = cv::Vec3b(   0,   0, 255 );
	color[4] = cv::Vec3b( 255, 255,   0 );
	color[5] = cv::Vec3b( 255,   0, 255 );
	color[6] = cv::Vec3b(   0, 255, 255 );

	cv::namedWindow( "Color" );
	cv::namedWindow( "Depth" );
	cv::namedWindow( "Player" );
	cv::namedWindow( "Skeleton" );

	while( 1 ){
		// フレームの更新待ち
		ResetEvent( hColorEvent );
		ResetEvent( hDepthPlayerEvent );
		ResetEvent( hSkeletonEvent );
		WaitForMultipleObjects( ARRAYSIZE( hEvents ), hEvents, true, INFINITE );

		// Colorカメラからフレームを取得
		NUI_IMAGE_FRAME pColorImageFrame = { 0 };
		hResult = pSensor->NuiImageStreamGetNextFrame( hColorHandle, 0, &pColorImageFrame );
		if( FAILED( hResult ) ){
			std::cerr << "Error : NuiImageStreamGetNextFrame( COLOR )" << std::endl;
			return -1;
		}

		// Depthセンサーからフレームを取得
		NUI_IMAGE_FRAME pDepthPlayerImageFrame = { 0 };
		hResult = pSensor->NuiImageStreamGetNextFrame( hDepthPlayerHandle, 0, &pDepthPlayerImageFrame );
		if( FAILED( hResult ) ){
			std::cerr << "Error : NuiImageStreamGetNextFrame( DEPTH&PLAYER )" << std::endl;
			return -1;
		}

		// Skeletonフレームを取得
		NUI_SKELETON_FRAME pSkeletonFrame = { 0 };
		hResult = pSensor->NuiSkeletonGetNextFrame( 0, &pSkeletonFrame );
		if( FAILED( hResult ) ){
			std::cout << "Error : NuiSkeletonGetNextFrame" << std::endl;
			return -1;
		}

		// Color画像データの取得
		INuiFrameTexture* pColorFrameTexture = pColorImageFrame.pFrameTexture;
		NUI_LOCKED_RECT sColorLockedRect;
		pColorFrameTexture->LockRect( 0, &sColorLockedRect, nullptr, 0 );

		// Depthデータの取得
		INuiFrameTexture* pDepthPlayerFrameTexture = pDepthPlayerImageFrame.pFrameTexture;
		NUI_LOCKED_RECT sDepthPlayerLockedRect;
		pDepthPlayerFrameTexture->LockRect( 0, &sDepthPlayerLockedRect, nullptr, 0 );

		// 表示
		cv::Mat colorMat( 480, 640, CV_8UC4, reinterpret_cast<uchar*>( sColorLockedRect.pBits ) );

		LONG registX = 0;
		LONG registY = 0;
		ushort* pBuffer = reinterpret_cast<ushort*>( sDepthPlayerLockedRect.pBits );
		cv::Mat bufferMat = cv::Mat::zeros( 480, 640, CV_16UC1 );
		cv::Mat playerMat = cv::Mat::zeros( 480, 640, CV_8UC3 );
		for( int y = 0; y < 480; y++ ){
			for( int x = 0; x < 640; x++ ){
				pSensor->NuiImageGetColorPixelCoordinatesFromDepthPixelAtResolution( NUI_IMAGE_RESOLUTION_640x480, NUI_IMAGE_RESOLUTION_640x480, nullptr, x, y, *pBuffer, &registX, &registY );
				if( ( registX >= 0 ) && ( registX < 640 ) && ( registY >= 0 ) && ( registY < 480 ) ){
					bufferMat.at<ushort>( registY, registX ) = *pBuffer & 0xFFF8;
					playerMat.at<cv::Vec3b>( registY, registX ) = color[*pBuffer & 0x7];
				}
				pBuffer++;
			}
		}
		cv::Mat depthMat( 480, 640, CV_8UC1 );
		bufferMat.convertTo( depthMat, CV_8UC3, -255.0f / NUI_IMAGE_DEPTH_MAXIMUM, 255.0f );

		cv::Mat skeletonMat = cv::Mat::zeros( 480, 640, CV_8UC3 );
		cv::Point2f point;
		for( int count = 0; count < NUI_SKELETON_COUNT; count++ ){
			NUI_SKELETON_DATA skeleton = pSkeletonFrame.SkeletonData[count];
			if( skeleton.eTrackingState == NUI_SKELETON_TRACKED ){
				for( int position = 0; position < NUI_SKELETON_POSITION_COUNT; position++ ){
					NuiTransformSkeletonToDepthImage( skeleton.SkeletonPositions[position], &point.x, &point.y, NUI_IMAGE_RESOLUTION_640x480 );
					cv::circle( skeletonMat, point, 10, static_cast<cv::Scalar>( color[count + 1] ), -1, CV_AA );
				}
			}
		}
		
		cv::imshow( "Color", colorMat );
		cv::imshow( "Depth", depthMat );
		cv::imshow( "Player", playerMat );
		cv::imshow( "Skeleton", skeletonMat );

		// フレームの解放
		pColorFrameTexture->UnlockRect( 0 );
		pDepthPlayerFrameTexture->UnlockRect( 0 );
		pSensor->NuiImageStreamReleaseFrame( hColorHandle, &pColorImageFrame );
		pSensor->NuiImageStreamReleaseFrame( hDepthPlayerHandle, &pDepthPlayerImageFrame );

		// ループの終了判定(Escキー)
		if( cv::waitKey( 30 ) == VK_ESCAPE ){
			break;
		}
	}

	// Kinectの終了処理
	pSensor->NuiShutdown();
	pSensor->NuiSkeletonTrackingDisable();
	CloseHandle( hColorEvent );
	CloseHandle( hDepthPlayerEvent );
	CloseHandle( hSkeletonEvent );
	CloseHandle( hColorHandle );
	CloseHandle( hDepthPlayerHandle );

	cv::destroyAllWindows();

	return 0;
}
Exemplo n.º 25
0
   void
   SMTPDeliveryManager::DoWork()
   //---------------------------------------------------------------------------()
   // DESCRIPTION:
   // Responsible for creating threads to deliver messages.
   //---------------------------------------------------------------------------()
   {
      LOG_DEBUG("SMTPDeliveryManager::Start()");

      // Unlock all messages
      PersistentMessage::UnlockAll();

      shared_ptr<WorkQueue> pQueue = WorkQueueManager::Instance()->GetQueue(GetQueueName());

      while (1)
      {
         // Deliver all pending messages
         shared_ptr<Message> pMessage;
         while (pMessage = _GetNextMessage())
         {
            // Lock this message
            if (!PersistentMessage::LockObject(pMessage))
            {
               // Failed to lock the message.
               ErrorManager::Instance()->ReportError(ErrorManager::Critical, 4216, "SMTPDeliveryManager::DoWork", "Failed to lock message.");
               continue;
            }

            shared_ptr<DeliveryTask> pDeliveryTask = shared_ptr<DeliveryTask>(new DeliveryTask(pMessage));
            WorkQueueManager::Instance()->AddTask(m_iQueueID, pDeliveryTask);
            
            m_lCurNumberOfSent++;

            _SendStatistics();

            ServerStatus::Instance()->OnMessageProcessed();
         }

         _StartTimer();

         const int iSize = 3;
         HANDLE handles[iSize];

         handles[0] = m_hStopRequest.GetHandle();
         handles[1] = m_evtDeliverMessage.GetHandle();
         handles[2] = m_evtTimer;
      
         DWORD dwWaitResult = WaitForMultipleObjects(iSize, handles, FALSE, INFINITE);

         int iEvent = dwWaitResult - WAIT_OBJECT_0;

         // Temp test to see if cause of IOCP errors

         if (iEvent < 0)
         {

            ErrorManager::Instance()->ReportError(ErrorManager::Critical, 9999, "SMTPDeliveryManager::DoWork", "WARNING iEvent less than 0!");
            m_evtDeliverMessage.Reset();
            return;
         }
         else
         {
         switch (iEvent)
         {
         case 0:
            // We should stop now
            _SendStatistics(true);
            return;
         case 1:
            // --- Reset the event to give someone else the chance to 
            //     sending emails.
            m_evtDeliverMessage.Reset();
            break;
         }
}
      }

      _SendStatistics(true);
      
      
      return;
   }
static unsigned int __stdcall ioThread(void* inst)
{
	rDeviceERHandPeakCAN* devCAN = (rDeviceERHandPeakCAN*)inst;

	HANDLE hEvents[2];
	int eventIdx;
	char id_des;
	char id_cmd;
	char id_src;
	int len;
	unsigned char data[8];
	unsigned char data_return = 0;
    
    // Configure events to be listened on
    hEvents[0] = devCAN->_ioQuitEvent;
	hEvents[1] = devCAN->_ioEvent;
	

	while (devCAN->_ioThreadRun)
	{
		eventIdx = WaitForMultipleObjects(sizeof(hEvents)/sizeof(hEvents[0]), hEvents, FALSE, 300); 

		switch (eventIdx)
		{
		case 0:
			return 0;//break;

		case 1:
			{
				while (0 == CANAPI::get_message(devCAN->_CAN_Ch, &id_cmd, &id_src, &id_des, &len, data, FALSE))
				{
					switch (id_cmd)
					{
					case ID_CMD_QUERY_CONTROL_DATA:
						{
							if (id_src >= ID_DEVICE_SUB_01 && id_src <= ID_DEVICE_SUB_04)
							{
								devCAN->_lock.lock();
								{
									devCAN->_vars->enc_actual[(id_src-ID_DEVICE_SUB_01)*4 + 0] = (int)(data[0] | (data[1] << 8));
									devCAN->_vars->enc_actual[(id_src-ID_DEVICE_SUB_01)*4 + 1] = (int)(data[2] | (data[3] << 8));
									devCAN->_vars->enc_actual[(id_src-ID_DEVICE_SUB_01)*4 + 2] = (int)(data[4] | (data[5] << 8));
									devCAN->_vars->enc_actual[(id_src-ID_DEVICE_SUB_01)*4 + 3] = (int)(data[6] | (data[7] << 8));
									data_return |= (0x01 << (id_src-ID_DEVICE_SUB_01));
								}
								devCAN->_lock.unlock();
							}
							if (data_return == (0x01 | 0x02 | 0x04 | 0x08))
							{
								devCAN->_lock.lock();
								{
									// send torques
									for (int i=0; i<4;i++)
									{
										CANAPI::write_current(devCAN->_CAN_Ch, i, &devCAN->_vars->pwm_demand[4*i]);
										for(int k=0; k<100000; k++);
									}
								}
								devCAN->_lock.unlock();

								data_return = 0;
							}
						}
						break;
					}
				}
			}
			break;
		}
	}

	return 0;
}
Exemplo n.º 27
0
DWORD CDBPSServer::StartServer(DWORD dwPort, DWORD dwNumberOfConnection)
{
	/*
		Server have to be give a port for itself from Server Administrator
	*/
	DWORD dwRet = E_RET_SUCCESS;
	dwRet = InitServerSock(dwPort);
	if (dwRet != E_RET_SUCCESS) {
		ErrorLog("Fail to initailize Server Sock");
		return E_RET_FAIL;
	}

	/*
		Create Completion Port for opertation IOCP.
		the variable 0 mean that IOCP set value itself.
	*/
	dwRet = InitIOCompletionPort(0);
	if (dwRet != E_RET_SUCCESS) {
		ErrorLog("Fail to initailize Server Sock");
		return E_RET_FAIL;
	}

	/*
		Make worker threads for operating IOCP
	*/
	dwRet = InitWorkerThread();
	if (dwRet != E_RET_SUCCESS) {
		ErrorLog("Fail to initailize Server Sock");
		return E_RET_FAIL;
	}

	dwRet = InitDBCQueue(dwNumberOfConnection);
	if (dwRet != E_RET_SUCCESS) {
		ErrorLog("Fail to initailize DB Connection Queue");
		return E_RET_FAIL;
	}


	dwRet = InitServerValue(dwPort);
	if (dwRet != E_RET_SUCCESS) {
		ErrorLog("Fail to configure server value");
		return E_RET_FAIL;
	}

	m_bStartServer = TRUE;
	while (m_bStartServer)
	{
		try
		{
			ST_CLIENT_SOCKET stClientSocket;
			dwRet = AcceptServer(stClientSocket);
			if (dwRet != E_RET_SUCCESS) {
				continue;
			}

			dwRet = CompleteReadFromClient(stClientSocket);
			if (dwRet != E_RET_SUCCESS) {
				continue;
			}
		}
		catch (std::exception &e)
		{
			/*
				Abnormally Exception
			*/
			ErrorLog("%s", e.what());
			DestoryDBCQueue(dwNumberOfConnection);
			return dwRet;
		}
	}

	/*
		All Thread is waiting for stopping their operation
	*/
	WaitForMultipleObjects(m_stServerWorkerThreads.dwNumberOfThread, m_stServerWorkerThreads.phWorkerThread, TRUE, INFINITE);
	DestoryDBCQueue(dwNumberOfConnection);
	
	return dwRet;
}
Exemplo n.º 28
0
void *
vncDesktopThread::run_undetached(void *arg)
{
	//*******************************************************
	// INIT
	//*******************************************************
	capture=true;
	vnclog.Print(LL_INTERR, VNCLOG("Hook changed 1\n"));
	// Save the thread's "home" desktop, under NT (no effect under 9x)
	m_desktop->m_home_desktop = GetThreadDesktop(GetCurrentThreadId());
    vnclog.Print(LL_INTERR, VNCLOG("Hook changed 2\n"));
	// Attempt to initialise and return success or failure
	m_desktop->KillScreenSaver();
	{
		keybd_event(VK_CONTROL, 0, 0, 0);
        keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0);
		Sleep(500); //Give screen some time to kill screensaver
	}
    DWORD startup_error;
	if ((startup_error = m_desktop->Startup()) != 0)
	{
		//TAG14
		vncService::SelectHDESK(m_desktop->m_home_desktop);
		if (m_desktop->m_input_desktop)
			CloseDesktop(m_desktop->m_input_desktop);
		ReturnVal(startup_error);
		return NULL;
	}
	// Succeeded to initialise ok
	ReturnVal(0);

	// sf@2003 - Done here to take into account if the driver is actually activated
	m_desktop->InitHookSettings(); 

	// We set a flag inside the desktop handler here, to indicate it's now safe
	// to handle clipboard messages
	m_desktop->SetClipboardActive(TRUE);

	// All changes in the state of the display are stored in a local
	// UpdateTracker object, and are flushed to the vncServer whenever
	// client updates are about to be triggered
	rfb::SimpleUpdateTracker clipped_updates;
	rfb::ClippedUpdateTracker updates(clipped_updates, m_desktop->m_Cliprect);
	clipped_updates.enable_copyrect(true);
	rfb::Region2D rgncache;


	// Incoming update messages are collated into a single region cache
	// The region cache areas are checked for changes before an update
	// is triggered, and the changed areas are passed to the UpdateTracker
	rgncache = m_desktop->m_Cliprect;
	m_server->SetScreenOffset(m_desktop->m_ScreenOffsetx,m_desktop->m_ScreenOffsety,m_desktop->nr_monitors);

	// The previous cursor position is stored, to allow us to erase the
	// old instance whenever it moves.
	rfb::Point oldcursorpos;

	// The driver gives smaller rectangles to check
	// if Accuracy is 4 you eliminate pointer updates
	if (m_desktop->VideoBuffer() && m_desktop->m_hookdriver)
		m_desktop->m_buffer.SetAccuracy(4);

	//init vars
	m_desktop->m_SWSizeChanged=FALSE;
	m_desktop->m_SWtoDesktop=FALSE;
	m_desktop->m_SWmoved=FALSE;
	m_desktop->Hookdll_Changed = true;
	m_desktop->m_displaychanged=false;
	m_desktop->m_hookswitch=false;
	m_desktop->m_hookinited = FALSE;

	// Set driver cursor state
	XRichCursorEnabled= (FALSE != m_desktop->m_server->IsXRichCursorEnabled());
	if (!XRichCursorEnabled && m_desktop->m_videodriver) m_desktop->m_videodriver->HardwareCursor();
	if (XRichCursorEnabled && m_desktop->m_videodriver) m_desktop->m_videodriver->NoHardwareCursor();
	if (XRichCursorEnabled) m_server->UpdateCursorShape();

	InvalidateRect(NULL,NULL,TRUE);
	oldtick=timeGetTime();
	int fullpollcounter=0;
	//*******************************************************
	// END INIT
	//*******************************************************
	// START PROCESSING DESKTOP MESSAGES
	/////////////////////
	HANDLE threadHandle=NULL;
	stop_hookwatch=false;
	/////////////////////
	// We use a dynmiac value based on cpu usage
    //DWORD MIN_UPDATE_INTERVAL=33;
	/////////////////////
	bool looping=true;
	int waiting_update=0;
	SetEvent(m_desktop->restart_event);
	///
	Sleep(1000);
	rgncache.assign_union(rfb::Region2D(m_desktop->m_Cliprect));
	if (m_desktop->VideoBuffer() && m_desktop->m_hookdriver)
											{
												m_desktop->m_buffer.GrabRegion(rgncache,true,true);
											}
										else
											{
												m_desktop->m_buffer.GrabRegion(rgncache,false,true);
											}
	///
	while (looping && !fShutdownOrdered)
	{		
		DWORD result;
		newtick = timeGetTime();
		int waittime;
		waittime=100-(newtick-oldtick);
		if (m_desktop->VideoBuffer() && m_desktop->m_hookdriver) 
		{
			int fastcounter=0;
			POINT cursorpos;
			while (m_desktop->m_videodriver->oldaantal==m_desktop->pchanges_buf->counter)
			{
				Sleep(5);
				fastcounter++;
				if (fastcounter>20)
				{
					#ifdef _DEBUG
										char			szText[256];
										sprintf(szText,"fastcounter\n");
										OutputDebugString(szText);		
					#endif
					break;
				}
				if (GetCursorPos(&cursorpos) && 
										((cursorpos.x != oldcursorpos.x) ||
										(cursorpos.y != oldcursorpos.y))) break;
			}
			waittime=0;
		}
		else
		{
			waittime=waittime-(waiting_update*10);
		}
		if (waittime<0) waittime=0;
		if (waittime>100) waittime=100;

		result=WaitForMultipleObjects(6,m_desktop->trigger_events,FALSE,waittime);
		{
			//#ifdef _DEBUG
			//							char			szText[256];
			//							sprintf(szText,"WaitForMultipleObjects %i\n",result );
			//							OutputDebugString(szText);		
			//#endif

			// We need to wait until restart is done
			// else wait_timeout goes in to looping while sink window is not ready
			// if no window could be started in 10 seconds something went wrong, close
			// desktop thread.
			DWORD status=WaitForSingleObject(m_desktop->restart_event,10000);
			if (status==WAIT_TIMEOUT) looping=false;
			switch(result)
			{
				case WAIT_TIMEOUT:
				case WAIT_OBJECT_0:
				{
				waiting_update=0;
				ResetEvent(m_desktop->trigger_events[0]);
							{
								//measure current cpu usage of winvnc
								cpuUsage = usage.GetUsage();
								if (cpuUsage > m_server->MaxCpu()) 
									MIN_UPDATE_INTERVAL+=10;
								else MIN_UPDATE_INTERVAL-=10;
								if (MIN_UPDATE_INTERVAL<MIN_UPDATE_INTERVAL_MIN) MIN_UPDATE_INTERVAL=MIN_UPDATE_INTERVAL_MIN;
								if (MIN_UPDATE_INTERVAL>MIN_UPDATE_INTERVAL_MAX) MIN_UPDATE_INTERVAL=MIN_UPDATE_INTERVAL_MAX;


					//			vnclog.Print(LL_INTERR, VNCLOG("!PeekMessage \n"));
								// MAX 30fps
								newtick = timeGetTime(); // Better resolution than GetTickCount ;)
								if ((newtick-oldtick)<MIN_UPDATE_INTERVAL)
								{
									Sleep(MIN_UPDATE_INTERVAL-(newtick-oldtick));
									//continue;  Verify, this can cause screen lockup
									// We need another PeekMessage, but this is only done
									// by hookdll and viewer asking for new update
									// can cause a very long wait time
								}	
								
								#ifdef _DEBUG
										char			szText[256];
										sprintf(szText," cpu2: %d %i %i\n",cpuUsage,MIN_UPDATE_INTERVAL,newtick-oldtick);
										OutputDebugString(szText);		
								#endif
								oldtick=newtick;
								if (m_desktop->VideoBuffer() && m_desktop->m_hookdriver) handle_driver_changes(rgncache,updates);
								m_desktop->m_update_triggered = FALSE;
								g_update_triggered = FALSE;
								//if (m_desktop->m_timerid==NULL) m_desktop->m_timerid = SetTimer(m_desktop->m_hwnd, 1, 100, NULL);

								//*******************************************************
								// HOOKDLL START STOP need to be executed from the thread
								//*******************************************************
								if (m_desktop->Hookdll_Changed && !m_desktop->m_hookswitch)
								{
									vnclog.Print(LL_INTERR, VNCLOG("Hook changed \n"));
									m_desktop->StartStophookdll(m_desktop->On_Off_hookdll);
									if (m_desktop->On_Off_hookdll)
										m_desktop->m_hOldcursor = NULL; // Force mouse cursor grabbing if hookdll On
									// Todo: in case of hookdriver Off - Hoodll On -> hookdriver On - Hoodll Off
									// we must send an empty mouse cursor to the clients so they get rid of their local
									// mouse cursor bitmap
									m_desktop->Hookdll_Changed=false;
								}
								//*******************************************************
								// SCREEN DISPLAY HAS CHANGED, RESTART DRIVER (IF Used)
								//*******************************************************
								if (!m_server->IsThereFileTransBusy())
									if (!handle_display_change(threadHandle, rgncache, clipped_updates, updates))
									{
										//failed we need to quit thread
										looping=false;
										break;
									}
								//*******************************************************
								// END SCREEN DISPLAY HAS CHANGED
								//*******************************************************
					//			m_server->SetSWOffset(m_desktop->m_SWOffsetx,m_desktop->m_SWOffsety);
							
								//*******************************************************************
								// SINGLE WINDOW 
								// size SW changed
								// Position change -->change offsets
								//*******************************************************************
								bool SWSizeChanged=false;
								if (m_server->SingleWindow())
								{
									omni_mutex_lock l(m_desktop->m_update_lock);
									m_desktop->GetQuarterSize();
									m_server->SetSWOffset(m_desktop->m_SWOffsetx,m_desktop->m_SWOffsety);
									//SW size changed
									if (m_desktop->m_SWSizeChanged)
									{
										SWSizeChanged=true;
										m_desktop->m_SWSizeChanged=FALSE;
										m_desktop->GetQuarterSize();
										rgncache.assign_union(rfb::Region2D(m_desktop->m_Cliprect));
					//					vnclog.Print(LL_INTINFO, VNCLOG("4 %i %i %i %i \n"),m_desktop->m_Cliprect.br.x,m_desktop->m_Cliprect.br.y,m_desktop->m_Cliprect.tl.x,m_desktop->m_Cliprect.tl.y);
										updates.set_clip_region(m_desktop->m_Cliprect);
										m_server->SetSWOffset(m_desktop->m_SWOffsetx,m_desktop->m_SWOffsety);				
										m_desktop->m_buffer.ClearCache();
										m_desktop->m_buffer.BlackBack();
									}
									//SW position changed
									if (m_desktop->m_SWmoved)
									{
										m_desktop->m_SWmoved=FALSE;
										updates.set_clip_region(m_desktop->m_Cliprect);
										m_server->SetSWOffset(m_desktop->m_SWOffsetx,m_desktop->m_SWOffsety);				
										rgncache.assign_union(rfb::Region2D(m_desktop->m_Cliprect));
					//					vnclog.Print(LL_INTINFO, VNCLOG("5 %i %i %i %i \n"),m_desktop->m_Cliprect.br.x,m_desktop->m_Cliprect.br.y,m_desktop->m_Cliprect.tl.x,m_desktop->m_Cliprect.tl.y);
										m_desktop->m_buffer.ClearCache();
										m_desktop->m_buffer.BlackBack();
									}

								if (m_server->SingleWindow() && SWSizeChanged)
									{
										m_server->SetNewSWSize(m_desktop->m_SWWidth,m_desktop->m_SWHeight,FALSE);
										m_server->SetScreenOffset(m_desktop->m_ScreenOffsetx,m_desktop->m_ScreenOffsety,m_desktop->nr_monitors);
									}
								}// end update lock
								
								////////////////////////////////////////////////////////////////////////////////
								// END DYNAMIC CHANGES
								////////////////////////////////////////////////////////////////////////////////

								//Beep(1000,10);
								//
								// CALCULATE CHANGES
								m_desktop->m_UltraEncoder_used=m_desktop->m_server->IsThereAUltraEncodingClient();
					//			vnclog.Print(LL_INTERR, VNCLOG("UpdateWanted B\n"));
//#ifdef _DEBUG
////										char			szText[256];
//									sprintf(szText," m_desktop->m_server->UpdateWanted check\n");
//										OutputDebugString(szText);		
//#endif
								omni_mutex_lock l(m_desktop->m_update_lock);
								if (m_desktop->m_server->UpdateWanted())
								{
					//				vnclog.Print(LL_INTERR, VNCLOG("UpdateWanted N\n"));
									//TEST4
									// Re-render the mouse's old location if it's moved
									bool cursormoved = false;
									POINT cursorpos;
									if (GetCursorPos(&cursorpos) && 
										((cursorpos.x != oldcursorpos.x) ||
										(cursorpos.y != oldcursorpos.y)))
									{
					//					vnclog.Print(LL_INTERR, VNCLOG("UpdateWanted M %i %i %i %i\n"),cursorpos.x, oldcursorpos.x,cursorpos.y,oldcursorpos.y);
										cursormoved = TRUE;
										oldcursorpos = rfb::Point(cursorpos);
										// nyama/marscha - PointerPos. Inform clients about mouse move.
										m_desktop->m_server->UpdateMouse();
										if (MyGetCursorInfo)
										{
											MyCURSORINFO cinfo;
											cinfo.cbSize=sizeof(MyCURSORINFO);
											MyGetCursorInfo(&cinfo);
											m_desktop->SetCursor(cinfo.hCursor);
										}
									}
								
									//****************************************************************************
									//************* Polling ---- no driver
									//****************************************************************************
									if (!m_desktop->m_hookdriver || !m_desktop->can_be_hooked)
									{
										do_polling(threadHandle, rgncache, fullpollcounter, cursormoved);
									}
									//****************************************************************************
									//************* driver  No polling
									//****************************************************************************
									else 
									{
										// long lTime = timeGetTime();
										if (cursormoved)
										{
											// if (lTime - m_desktop->m_lLastMouseUpdateTime < 200)
											// 	continue;
											m_desktop->m_buffer.SetAccuracy(m_desktop->m_server->TurboMode() ? 2 : 1);
											// m_desktop->m_lLastMouseUpdateTime = lTime;
										}
										else
											// 4 is not that bad...but not perfect (especially with tree branchs display)
											m_desktop->m_buffer.SetAccuracy(m_desktop->m_server->TurboMode() ? 4 : 2); 
									}
									
									
									// PROCESS THE MOUSE POINTER
									// Some of the hard work is done in clients, some here
									// This code fetches the desktop under the old pointer position
									// but the client is responsible for actually encoding and sending
									// it when required.
									// This code also renders the pointer and saves the rendered position
									// Clients include this when rendering updates.
									// The code is complicated in this way because we wish to avoid 
									// rendering parts of the screen the mouse moved through between
									// client updates, since in practice they will probably not have changed.
								
									if (cursormoved && !m_desktop->m_hookdriver)
										{
											if (!m_desktop->m_cursorpos.is_empty())
											{
												// Cursor position seems to be outsite the bounding
												// When you make the screen smaller
												// add extra check
												rfb::Rect rect;
												int x = m_desktop->m_cursorpos.tl.x;
												int w = m_desktop->m_cursorpos.br.x-x;
												int y = m_desktop->m_cursorpos.tl.y;
												int h = m_desktop->m_cursorpos.br.y-y;
												if (ClipRect(&x, &y, &w, &h, m_desktop->m_bmrect.tl.x, m_desktop->m_bmrect.tl.y,
													m_desktop->m_bmrect.br.x-m_desktop->m_bmrect.tl.x, m_desktop->m_bmrect.br.y-m_desktop->m_bmrect.tl.y))
													{
														rect.tl.x = x;
														rect.br.x = x+w;
														rect.tl.y = y;
														rect.br.y = y+h;
														rgncache.assign_union(rect);
					//									vnclog.Print(LL_INTINFO, VNCLOG("6 %i %i %i %i \n"),m_desktop->m_cursorpos.br.x,m_desktop->m_cursorpos.br.y,m_desktop->m_cursorpos.tl.x,m_desktop->m_cursorpos.tl.y);
					//									vnclog.Print(LL_INTINFO, VNCLOG("6 %i %i %i %i \n"),rect.br.x,rect.br.y,rect.tl.x,rect.tl.y);
													}
											}

										}
									

									{
										// Prevent any clients from accessing the Buffer
										omni_mutex_lock l(m_desktop->m_update_lock);
										
										// CHECK FOR COPYRECTS
										// This actually just checks where the Foreground window is
										if (!m_desktop->m_hookdriver && !m_server->SingleWindow()) 
											m_desktop->CalcCopyRects(updates);
										
										// GRAB THE DISPLAY
										// Fetch data from the display to our display cache.
										// Update the scaled rects when using server side scaling
										// something wrong inithooking again
										// We make sure no updates are in the regions
										// sf@2002 - Added "&& m_desktop->m_hookdriver"
										// Otherwise we're still getting driver updates (from shared memory buffer)
										// after a m_hookdriver switching from on to off 
										// (and m_hookdll from off to on) that causes mouse cursor garbage,
										// or missing mouse cursor.
										if (m_desktop->VideoBuffer() && m_desktop->m_hookdriver)
											{
												m_desktop->m_buffer.GrabRegion(rgncache,true,capture);
											}
										else
											{
												m_desktop->m_buffer.GrabRegion(rgncache,false,capture);
											}
#ifdef _DEBUG
										char			szText[256];
										sprintf(szText," capture %i\n",capture);
										OutputDebugString(szText);		
#endif
										capture=true;
											
										// sf@2002 - v1.1.x - Mouse handling
										// If one client, send cursor shapes only when the cursor changes.
										// This is Disabled for now.
										if( !XRichCursorEnabled==m_desktop->m_server->IsXRichCursorEnabled())
											{
												XRichCursorEnabled= (FALSE != m_desktop->m_server->IsXRichCursorEnabled());
												if (m_desktop->m_videodriver)
														{
																if (!XRichCursorEnabled) m_desktop->m_videodriver->HardwareCursor();
																else m_desktop->m_videodriver->NoHardwareCursor();
														}

											}
										if (m_desktop->m_server->IsXRichCursorEnabled() && !m_desktop->m_UltraEncoder_used)
											{
												if (m_desktop->m_hcursor != m_desktop->m_hOldcursor || m_desktop->m_buffer.IsShapeCleared())
														{
																m_desktop->m_hOldcursor = m_desktop->m_hcursor;
																m_desktop->m_buffer.SetCursorPending(TRUE);
																if (!m_desktop->m_hookdriver) m_desktop->m_buffer.GrabMouse(); // Grab mouse cursor in all cases
																m_desktop->m_server->UpdateMouse();
																rfb::Rect rect;
																int x = m_desktop->m_cursorpos.tl.x;
																int w = m_desktop->m_cursorpos.br.x-x;
																int y = m_desktop->m_cursorpos.tl.y;
																int h = m_desktop->m_cursorpos.br.y-y;
																if (ClipRect(&x, &y, &w, &h, m_desktop->m_bmrect.tl.x, m_desktop->m_bmrect.tl.y,
																	m_desktop->m_bmrect.br.x-m_desktop->m_bmrect.tl.x, m_desktop->m_bmrect.br.y-m_desktop->m_bmrect.tl.y))
																		{
																			rect.tl.x = x;
																			rect.br.x = x+w;
																			rect.tl.y = y;
																			rect.br.y = y+h;
																			rgncache.assign_union(rect);
					//														vnclog.Print(LL_INTINFO, VNCLOG("7 %i %i %i %i \n"),m_desktop->m_cursorpos.br.x,m_desktop->m_cursorpos.br.y,m_desktop->m_cursorpos.tl.x,m_desktop->m_cursorpos.tl.y);
					//														vnclog.Print(LL_INTINFO, VNCLOG("6 %i %i %i %i \n"),rect.br.x,rect.br.y,rect.tl.x,rect.tl.y);
																		}
																m_server->UpdateCursorShape();
																}
											}
										else if (!m_desktop->m_hookdriver)// If several clients, send them all the mouse updates
											{												
												// Render the mouse
												//if (!m_desktop->VideoBuffer())
												m_desktop->m_buffer.GrabMouse();
												
												if (cursormoved /*&& !m_desktop->m_buffer.IsCursorUpdatePending()*/) 
															{
																// Inform clients that it has moved
																m_desktop->m_server->UpdateMouse();
																// Get the buffer to fetch the pointer bitmap
																if (!m_desktop->m_cursorpos.is_empty())
																{
																	rfb::Rect rect;
																int x = m_desktop->m_cursorpos.tl.x;
																int w = m_desktop->m_cursorpos.br.x-x;
																int y = m_desktop->m_cursorpos.tl.y;
																int h = m_desktop->m_cursorpos.br.y-y;
																if (ClipRect(&x, &y, &w, &h, m_desktop->m_bmrect.tl.x, m_desktop->m_bmrect.tl.y,
																	m_desktop->m_bmrect.br.x-m_desktop->m_bmrect.tl.x, m_desktop->m_bmrect.br.y-m_desktop->m_bmrect.tl.y))
																		{
																			rect.tl.x = x;
																			rect.br.x = x+w;
																			rect.tl.y = y;
																			rect.br.y = y+h;
																			rgncache.assign_union(rect);
																			vnclog.Print(LL_INTINFO, VNCLOG("8 %i %i %i %i \n"),m_desktop->m_cursorpos.br.x,m_desktop->m_cursorpos.br.y,m_desktop->m_cursorpos.tl.x,m_desktop->m_cursorpos.tl.y);
																			vnclog.Print(LL_INTINFO, VNCLOG("8 %i %i %i %i \n"),rect.br.x,rect.br.y,rect.tl.x,rect.tl.y);
																		}
																}

															}
												}	
										
											
										// SCAN THE CHANGED REGION FOR ACTUAL CHANGES
										// The hooks return hints as to areas that may have changed.
										// We check the suggested areas, and just send the ones that
										// have actually changed.
										// Note that we deliberately don't check the copyrect destination
										// here, to reduce the overhead & the likelihood of corrupting the
										// backbuffer contents.
										rfb::Region2D checkrgn;
										rfb::Region2D changedrgn;
										rfb::Region2D cachedrgn;

											
										//Update the backbuffer for the copyrect region
										if (!clipped_updates.get_copied_region().is_empty()) 
											{
												rfb::UpdateInfo update_info;
												rfb::RectVector::const_iterator i;
												clipped_updates.get_update(update_info);
												if (!update_info.copied.empty()) 
													{
														for (i=update_info.copied.begin(); i!=update_info.copied.end(); i++) 						
															m_desktop->m_buffer.CopyRect(*i, update_info.copy_delta);
													}
											}
										//Remove the copyrect region from the other updates					
										//checkrgn = rgncache.union_(clipped_updates.get_copied_region());	
										checkrgn = rgncache.subtract(clipped_updates.get_copied_region());	
										//make sure the copyrect is checked next update
										rgncache = clipped_updates.get_copied_region();
										//Check all regions for changed and cached parts
										//This is very cpu intensive, only check once for all viewers
										if (!checkrgn.is_empty())
											m_desktop->m_buffer.CheckRegion(changedrgn,cachedrgn, checkrgn);

										updates.add_changed(changedrgn);
										updates.add_cached(cachedrgn);
												
										clipped_updates.get_update(m_server->GetUpdateTracker());
									}  // end mutex lock

									// Clear the update tracker and region cache an solid
									clipped_updates.clear();
									// screen blanking
									if (m_desktop->OldPowerOffTimeout!=0)
										{
										if (!m_server->BlackAlphaBlending() || m_desktop->VideoBuffer())
											{
												if(OSversion()!=2)
												{
												SystemParametersInfo(SPI_SETPOWEROFFACTIVE, 1, NULL, 0);
												SendMessage(m_desktop->m_hwnd,WM_SYSCOMMAND,SC_MONITORPOWER,(LPARAM)2);
												}
					// don't block input here, this is the wrong thread!
											}
										}
					#ifdef AVILOG
									if (m_desktop->AviGen) m_desktop->AviGen->AddFrame((BYTE*)m_desktop->m_DIBbits);
					#endif
								}
								newtick = timeGetTime(); 
							}
						}
					break;

				case WAIT_OBJECT_0+1:
					ResetEvent(m_desktop->trigger_events[1]);
					m_desktop->lock_region_add=true;
					rgncache.assign_union(m_desktop->rgnpump);
					m_desktop->rgnpump.clear();
					m_desktop->lock_region_add=false;
					waiting_update++;
					break;
				case WAIT_OBJECT_0+2:
					ResetEvent(m_desktop->trigger_events[2]);
					break;
				case WAIT_OBJECT_0+3:
					if (MyGetCursorInfo)
					{
						MyCURSORINFO cinfo;
						cinfo.cbSize=sizeof(MyCURSORINFO);
						MyGetCursorInfo(&cinfo);
						m_desktop->SetCursor(cinfo.hCursor);
					}
					ResetEvent(m_desktop->trigger_events[3]);
					break;
				case WAIT_OBJECT_0+4:
					rgncache.assign_union(m_desktop->m_Cliprect);
					ResetEvent(m_desktop->trigger_events[4]);
					break;
				case WAIT_OBJECT_0+5:
					//break to close
					looping=false;
					ResetEvent(m_desktop->trigger_events[5]);
					break;
			}
		}
		
	}//while

	stop_hookwatch=true;
	if (threadHandle)
	{
		WaitForSingleObject( threadHandle, 5000 );
		CloseHandle(threadHandle);
	}
	
	m_desktop->SetClipboardActive(FALSE);
	vnclog.Print(LL_INTINFO, VNCLOG("quitting desktop server thread\n"));
	
	// Clear all the hooks and close windows, etc.
    m_desktop->SetBlockInputState(false);
	m_server->SingleWindow(false);
	vnclog.Print(LL_INTINFO, VNCLOG("quitting desktop server thread:SetBlockInputState\n"));
	
	// Clear the shift modifier keys, now that there are no remote clients
	vncKeymap::ClearShiftKeys();
	vnclog.Print(LL_INTINFO, VNCLOG("quitting desktop server thread:ClearShiftKeys\n"));
	
	// Switch back into our home desktop, under NT (no effect under 9x)
	//TAG14
	HWND mywin=FindWindow("blackscreen",NULL);
	if (mywin)SendMessage(mywin,WM_CLOSE, 0, 0);
	g_DesktopThread_running=false;
	vnclog.Print(LL_INTINFO, VNCLOG("quitting desktop server thread:g_DesktopThread_running=false\n"));
	m_desktop->Shutdown();
	vnclog.Print(LL_INTINFO, VNCLOG("quitting desktop server thread:m_desktop->Shutdown\n"));
	return NULL;
}
Exemplo n.º 29
0
bool	CAGuard::WaitFor(UInt64 inNanos)
{
	bool theAnswer = false;

#if TARGET_OS_MAC
	ThrowIf(!pthread_equal(pthread_self(), mOwner), CAException(1), "CAGuard::WaitFor: A thread has to have locked a guard be for it can wait");

	#if	Log_TimedWaits
		DebugMessageN1("CAGuard::WaitFor: waiting %.0f", (Float64)inNanos);
	#endif

	struct timespec	theTimeSpec;
	static const UInt64	kNanosPerSecond = 1000000000ULL;
	if(inNanos >= kNanosPerSecond)
	{
		theTimeSpec.tv_sec = static_cast<UInt32>(inNanos / kNanosPerSecond);
		theTimeSpec.tv_nsec = static_cast<UInt32>(inNanos % kNanosPerSecond);
	}
	else
	{
		theTimeSpec.tv_sec = 0;
		theTimeSpec.tv_nsec = static_cast<UInt32>(inNanos);
	}
	
	#if	Log_TimedWaits || Log_Latency || Log_Average_Latency
		UInt64	theStartNanos = CAHostTimeBase::GetCurrentTimeInNanos();
	#endif

	mOwner = 0;

	#if	Log_WaitOwnership
		DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAGuard::WaitFor: thread %p is waiting on %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), pthread_self(), mName, mOwner);
	#endif

	OSStatus theError = pthread_cond_timedwait_relative_np(&mCondVar, &mMutex, &theTimeSpec);
	ThrowIf((theError != 0) && (theError != ETIMEDOUT), CAException(theError), "CAGuard::WaitFor: Wait got an error");
	mOwner = pthread_self();
	
	#if	Log_TimedWaits || Log_Latency || Log_Average_Latency
		UInt64	theEndNanos = CAHostTimeBase::GetCurrentTimeInNanos();
	#endif
	
	#if	Log_TimedWaits
		DebugMessageN1("CAGuard::WaitFor: waited  %.0f", (Float64)(theEndNanos - theStartNanos));
	#endif
	
	#if	Log_Latency
		DebugMessageN1("CAGuard::WaitFor: latency  %.0f", (Float64)((theEndNanos - theStartNanos) - inNanos));
	#endif
	
	#if	Log_Average_Latency
		++mAverageLatencyCount;
		mAverageLatencyAccumulator += (theEndNanos - theStartNanos) - inNanos;
		if(mAverageLatencyCount >= 50)
		{
			DebugMessageN2("CAGuard::WaitFor: average latency  %.3f ns over %ld waits", mAverageLatencyAccumulator / mAverageLatencyCount, mAverageLatencyCount);
			mAverageLatencyCount = 0;
			mAverageLatencyAccumulator = 0.0;
		}
	#endif

	#if	Log_WaitOwnership
		DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAGuard::WaitFor: thread %p waited on %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), pthread_self(), mName, mOwner);
	#endif

	theAnswer = theError == ETIMEDOUT;
#elif TARGET_OS_WIN32
	ThrowIf(GetCurrentThreadId() != mOwner, CAException(1), "CAGuard::WaitFor: A thread has to have locked a guard be for it can wait");

	#if	Log_TimedWaits
		DebugMessageN1("CAGuard::WaitFor: waiting %.0f", (Float64)inNanos);
	#endif

	//	the time out is specified in milliseconds(!)
	UInt32 theWaitTime = static_cast<UInt32>(inNanos / 1000000ULL);

	#if	Log_TimedWaits || Log_Latency || Log_Average_Latency
		UInt64	theStartNanos = CAHostTimeBase::GetCurrentTimeInNanos();
	#endif

	mOwner = 0;

	#if	Log_WaitOwnership
		DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAGuard::WaitFor: thread %lu is waiting on %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner);
	#endif
	
	ReleaseMutex(mMutex);
	HANDLE theHandles[] = { mMutex, mEvent };
	OSStatus theError = WaitForMultipleObjects(2, theHandles, true, theWaitTime);
	ThrowIf((theError != WAIT_OBJECT_0) && (theError != WAIT_TIMEOUT), CAException(GetLastError()), "CAGuard::WaitFor: Wait got an error");
	mOwner = GetCurrentThreadId();
	ResetEvent(mEvent);
	
	#if	Log_TimedWaits || Log_Latency || Log_Average_Latency
		UInt64	theEndNanos = CAHostTimeBase::GetCurrentTimeInNanos();
	#endif
	
	#if	Log_TimedWaits
		DebugMessageN1("CAGuard::WaitFor: waited  %.0f", (Float64)(theEndNanos - theStartNanos));
	#endif
	
	#if	Log_Latency
		DebugMessageN1("CAGuard::WaitFor: latency  %.0f", (Float64)((theEndNanos - theStartNanos) - inNanos));
	#endif
	
	#if	Log_Average_Latency
		++mAverageLatencyCount;
		mAverageLatencyAccumulator += (theEndNanos - theStartNanos) - inNanos;
		if(mAverageLatencyCount >= 50)
		{
			DebugMessageN2("CAGuard::WaitFor: average latency  %.3f ns over %ld waits", mAverageLatencyAccumulator / mAverageLatencyCount, mAverageLatencyCount);
			mAverageLatencyCount = 0;
			mAverageLatencyAccumulator = 0.0;
		}
	#endif

	#if	Log_WaitOwnership
		DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAGuard::WaitFor: thread %lu waited on %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner);
	#endif

	theAnswer = theError == WAIT_TIMEOUT;
#endif

	return theAnswer;
}
Exemplo n.º 30
0
static void InOut(
   HANDLE hC0C,
   SOCKET hSock,
   Protocol &protocol,
   BOOL ignoreDSR,
   SOCKET hSockListen = INVALID_SOCKET)
{
  printf("InOut() START\n");

  protocol.Clean();

  BOOL stop = FALSE;

  enum {
    EVENT_READ,
    EVENT_SENT,
    EVENT_RECEIVED,
    EVENT_WRITTEN,
    EVENT_STAT,
    EVENT_CLOSE,
    EVENT_ACCEPT,
    EVENT_NUM
  };

  HANDLE hEvents[EVENT_NUM];
  OVERLAPPED overlaps[EVENT_NUM];

  if (!PrepareEvents(EVENT_NUM, hEvents, overlaps))
    stop = TRUE;

  if (!SetCommMask(hC0C, EV_DSR)) {
    TraceLastError("InOut(): SetCommMask()");
    stop = TRUE;
  }

  WSAEventSelect(hSock, hEvents[EVENT_CLOSE], FD_CLOSE);

  if (hSockListen != INVALID_SOCKET)
    WSAEventSelect(hSockListen, hEvents[EVENT_ACCEPT], FD_ACCEPT);

  DWORD not_used;

  BYTE cbufRead[64];
  BOOL waitingRead = FALSE;

  BYTE cbufSend[64];
  int cbufSendSize = 0;
  int cbufSendDone = 0;
  BOOL waitingSend = FALSE;

  BYTE cbufRecv[64];
  BOOL waitingRecv = FALSE;

  BYTE cbufWrite[64];
  int cbufWriteSize = 0;
  int cbufWriteDone = 0;
  BOOL waitingWrite = FALSE;

  BOOL waitingStat = FALSE;
  int DSR = -1;

  while (!stop) {
    if (!waitingSend) {
      if (!cbufSendSize) {
        cbufSendSize = protocol.Read(cbufSend, sizeof(cbufSend));
        if (cbufSendSize < 0)
          break;
      }

      DWORD num = cbufSendSize - cbufSendDone;

      if (num) {
        if (!WriteFile((HANDLE)hSock, cbufSend + cbufSendDone, num, &not_used, &overlaps[EVENT_SENT])) {
          if (::GetLastError() != ERROR_IO_PENDING) {
            TraceLastError("InOut(): WriteFile(hSock)");
            break;
          }
        }
        waitingSend = TRUE;
      }
    }

    if (!waitingRead && !protocol.isSendFull()) {
      if (!ReadFile(hC0C, cbufRead, sizeof(cbufRead), &not_used, &overlaps[EVENT_READ])) {
        if (::GetLastError() != ERROR_IO_PENDING) {
          TraceLastError("InOut(): ReadFile(hC0C)");
          break;
        }
      }
      waitingRead = TRUE;
    }

    if (!waitingWrite) {
      if (!cbufWriteSize) {
        cbufWriteSize = protocol.Recv(cbufWrite, sizeof(cbufWrite));
        if (cbufWriteSize < 0)
          break;
      }

      DWORD num = cbufWriteSize - cbufWriteDone;

      if (num) {
        if (!WriteFile(hC0C, cbufWrite + cbufWriteDone, num, &not_used, &overlaps[EVENT_WRITTEN])) {
          if (::GetLastError() != ERROR_IO_PENDING) {
            TraceLastError("InOut(): WriteFile(hC0C)");
            break;
          }
        }
        waitingWrite = TRUE;
      }
    }

    if (!waitingRecv && !protocol.isWriteFull()) {
      if (!ReadFile((HANDLE)hSock, cbufRecv, sizeof(cbufRecv), &not_used, &overlaps[EVENT_RECEIVED])) {
        if (::GetLastError() != ERROR_IO_PENDING) {
          TraceLastError("InOut(): ReadFile(hSock)");
          break;
        }
      }
      waitingRecv = TRUE;
    }

    if (!waitingStat) {
      if (!WaitCommEvent(hC0C, &not_used, &overlaps[EVENT_STAT])) {
        if (::GetLastError() != ERROR_IO_PENDING) {
          TraceLastError("InOut(): WaitCommEvent()");
          break;
        }
      }
      waitingStat = TRUE;

      DWORD stat;

      if (!GetCommModemStatus(hC0C, &stat)) {
        TraceLastError("InOut(): GetCommModemStatus()");
        break;
      }

      if (!(stat & MS_DSR_ON)) {
        if (DSR != 0) {
          printf("DSR is OFF\n");
          DSR = 0;
        }
        if (!ignoreDSR) {
          if (waitingSend)
            Sleep(1000);
          break;
        }
      } else {
        if (DSR != 1) {
          printf("DSR is ON\n");
          DSR = 1;
        }
      }
    }

    if ((waitingRead || waitingSend) && (waitingRecv || waitingWrite) && waitingStat) {
      DWORD done;

      switch (WaitForMultipleObjects(EVENT_NUM, hEvents, FALSE, 5000)) {
      case WAIT_OBJECT_0 + EVENT_READ:
        if (!GetOverlappedResult(hC0C, &overlaps[EVENT_READ], &done, FALSE)) {
          if (::GetLastError() != ERROR_OPERATION_ABORTED) {
            TraceLastError("InOut(): GetOverlappedResult(EVENT_READ)");
            stop = TRUE;
            break;
          }
        }
        ResetEvent(hEvents[EVENT_READ]);
        waitingRead = FALSE;
        protocol.Send(cbufRead, done);
        break;
      case WAIT_OBJECT_0 + EVENT_SENT:
        if (!GetOverlappedResult((HANDLE)hSock, &overlaps[EVENT_SENT], &done, FALSE)) {
          if (::GetLastError() != ERROR_OPERATION_ABORTED) {
            TraceLastError("InOut(): GetOverlappedResult(EVENT_SENT)");
            stop = TRUE;
            break;
          }
          done = 0;
        }
        ResetEvent(hEvents[EVENT_SENT]);
        cbufSendDone += done;
        if (cbufSendDone >= cbufSendSize)
          cbufSendDone = cbufSendSize = 0;
        waitingSend = FALSE;
        break;
      case WAIT_OBJECT_0 + EVENT_RECEIVED:
        if (!GetOverlappedResult((HANDLE)hSock, &overlaps[EVENT_RECEIVED], &done, FALSE)) {
          if (::GetLastError() != ERROR_OPERATION_ABORTED) {
            TraceLastError("InOut(): GetOverlappedResult(EVENT_RECEIVED)");
            stop = TRUE;
            break;
          }
          done = 0;
        } else if (!done) {
          ResetEvent(hEvents[EVENT_RECEIVED]);
          printf("Received EOF\n");
          break;
        }
        ResetEvent(hEvents[EVENT_RECEIVED]);
        waitingRecv = FALSE;
        protocol.Write(cbufRecv, done);
        break;
      case WAIT_OBJECT_0 + EVENT_WRITTEN:
        if (!GetOverlappedResult(hC0C, &overlaps[EVENT_WRITTEN], &done, FALSE)) {
          if (::GetLastError() != ERROR_OPERATION_ABORTED) {
            TraceLastError("InOut(): GetOverlappedResult(EVENT_WRITTEN)");
            stop = TRUE;
            break;
          }
          done = 0;
        }
        ResetEvent(hEvents[EVENT_WRITTEN]);
        cbufWriteDone += done;
        if (cbufWriteDone >= cbufWriteSize)
          cbufWriteDone = cbufWriteSize = 0;
        waitingWrite = FALSE;
        break;
      case WAIT_OBJECT_0 + EVENT_STAT:
        if (!GetOverlappedResult(hC0C, &overlaps[EVENT_STAT], &done, FALSE)) {
          if (::GetLastError() != ERROR_OPERATION_ABORTED) {
            TraceLastError("InOut(): GetOverlappedResult(EVENT_STAT)");
            stop = TRUE;
            break;
          }
        }
        waitingStat = FALSE;
        break;
      case WAIT_OBJECT_0 + EVENT_CLOSE:
        ResetEvent(hEvents[EVENT_CLOSE]);
        printf("EVENT_CLOSE\n");
        if (waitingWrite)
          Sleep(1000);
        stop = TRUE;
        break;
      case WAIT_OBJECT_0 + EVENT_ACCEPT: {
        ResetEvent(hEvents[EVENT_ACCEPT]);
        printf("EVENT_ACCEPT\n");

        SOCKET hSockTmp = Accept(hSockListen);

        if (hSockTmp != INVALID_SOCKET) {
          char msg[] = "*** Serial port is busy ***\n";

          send(hSockTmp, msg, strlen(msg), 0);
          Disconnect(hSockTmp);
        }
        break;
      }
      case WAIT_TIMEOUT:
        break;
      default:
        TraceLastError("InOut(): WaitForMultipleObjects()");
        stop = TRUE;
      }
    }
  }

  CancelIo(hC0C);
  CancelIo((HANDLE)hSock);

  if (hSockListen != INVALID_SOCKET) {
    WSAEventSelect(hSockListen, hEvents[EVENT_ACCEPT], 0);

    u_long blocking = 0;

    ioctlsocket(hSockListen, FIONBIO, &blocking);
  }

  CloseEvents(EVENT_NUM, hEvents);

  printf("InOut() - STOP\n");
}