Exemplo n.º 1
1
void resman_check_watch(struct resman *rman)
{
    struct watch_dir *wdir;
    unsigned int idx;

    unsigned int num_handles = dynarr_size(rman->watch_handles);
    if(!num_handles) {
        return;
    }

    idx = WaitForMultipleObjectsEx(num_handles, rman->watch_handles, FALSE, 0, TRUE);
    if(idx == WAIT_FAILED) {
        unsigned int err = GetLastError();
        fprintf(stderr, "failed to check for file modification: %u\n", err);
        return;
    }
    if(idx >= WAIT_OBJECT_0 && idx < WAIT_OBJECT_0 + num_handles) {
        if(!(wdir = rb_find(rman->wdirbyev, rman->watch_handles[idx]))) {
            fprintf(stderr, "got change handle, but failed to find corresponding watch_dir!\n");
            return;
        }

        handle_event(rman, rman->watch_handles[idx], wdir);

        /* restart the watch call */
        ReadDirectoryChangesW(wdir->handle, wdir->buf, RES_BUF_SIZE, FALSE, FILE_NOTIFY_CHANGE_LAST_WRITE, 0, &wdir->over, 0);
    }
}
Exemplo n.º 2
0
    //This function waits on two events jobReady or wakeAllBackgroundThreads
    //It first waits for 1sec and if it times out it will decommit the allocator and wait infinitely.
    bool BackgroundJobProcessor::WaitForJobReadyOrShutdown(ParallelThreadData *threadData)
    {
        const HANDLE handles[] = { jobReady.Handle(), wakeAllBackgroundThreads.Handle() };

        //Wait for 1 sec on jobReady and shutdownBackgroundThread events.
        unsigned int result = WaitForMultipleObjectsEx(_countof(handles), handles, false, 1000, false);

        while (result == WAIT_TIMEOUT)
        {
            if (threadData->CanDecommit())
            {
                // If its 1sec time out decommit and wait for INFINITE
                threadData->backgroundPageAllocator.DecommitNow();
                this->ForEachManager([&](JobManager *manager){
                    manager->OnDecommit(threadData);
                });
                result = WaitForMultipleObjectsEx(_countof(handles), handles, false, INFINITE, false);
            }
            else
            {
                result = WaitForMultipleObjectsEx(_countof(handles), handles, false, 1000, false);
            }
        }

        if (!(result == WAIT_OBJECT_0 || result == WAIT_OBJECT_0 + 1))
        {
            Js::Throw::FatalInternalError();
        }

        return result == WAIT_OBJECT_0;
    }
Exemplo n.º 3
0
/***********************************************************************
 *           MsgWaitForMultipleObjectsEx   ([email protected])
 */
DWORD X11DRV_MsgWaitForMultipleObjectsEx( DWORD count, const HANDLE *handles,
                                          DWORD timeout, DWORD mask, DWORD flags )
{
    DWORD i, ret;
    struct x11drv_thread_data *data = TlsGetValue( thread_data_tls_index );

    if (!data || data->process_event_count)
    {
        if (!count && !timeout) return WAIT_TIMEOUT;
        return WaitForMultipleObjectsEx( count, handles, flags & MWMO_WAITALL,
                                         timeout, flags & MWMO_ALERTABLE );
    }

    /* check whether only server queue handle was passed in */
    if (count < 2) flags &= ~MWMO_WAITALL;

    data->process_event_count++;

    if (process_events( data->display, mask )) ret = count;
    else if (count || timeout)
    {
        HANDLE new_handles[MAXIMUM_WAIT_OBJECTS+1];  /* FIXME! */

        for (i = 0; i < count; i++) new_handles[i] = handles[i];
        new_handles[count] = data->display_fd;

        ret = WaitForMultipleObjectsEx( count+1, new_handles, flags & MWMO_WAITALL,
                                        timeout, flags & MWMO_ALERTABLE );
        if (ret == count) process_events( data->display, mask );
    }
    else ret = WAIT_TIMEOUT;

    data->process_event_count--;
    return ret;
}
Exemplo n.º 4
0
Arquivo: event.c Projeto: AndreRH/wine
/***********************************************************************
 *              MsgWaitForMultipleObjectsEx   ([email protected])
 */
DWORD CDECL macdrv_MsgWaitForMultipleObjectsEx(DWORD count, const HANDLE *handles,
                                               DWORD timeout, DWORD mask, DWORD flags)
{
    DWORD ret;
    struct macdrv_thread_data *data = macdrv_thread_data();
    macdrv_event_mask event_mask = get_event_mask(mask);

    TRACE("count %d, handles %p, timeout %u, mask %x, flags %x\n", count,
          handles, timeout, mask, flags);

    if (!data)
    {
        if (!count && !timeout) return WAIT_TIMEOUT;
        return WaitForMultipleObjectsEx(count, handles, flags & MWMO_WAITALL,
                                        timeout, flags & MWMO_ALERTABLE);
    }

    if (data->current_event && data->current_event->type != QUERY_EVENT &&
        data->current_event->type != QUERY_EVENT_NO_PREEMPT_WAIT &&
        data->current_event->type != APP_QUIT_REQUESTED &&
        data->current_event->type != WINDOW_DRAG_BEGIN)
        event_mask = 0;  /* don't process nested events */

    if (process_events(data->queue, event_mask)) ret = count - 1;
    else if (count || timeout)
    {
        ret = WaitForMultipleObjectsEx(count, handles, flags & MWMO_WAITALL,
                                       timeout, flags & MWMO_ALERTABLE);
        if (ret == count - 1) process_events(data->queue, event_mask);
    }
    else ret = WAIT_TIMEOUT;

    return ret;
}
Exemplo n.º 5
0
void avanzar(int *posicion, int *carril, int color)
{
	int valor_devuelto, tpos = 0, tcarril = 0;
	int apos = *posicion;
	int acarril = *carril;
	HANDLE posiciones[3]; //Vamos a añadir los dif. eventos por los que esperaremos

						  //EVENTOS A ESPERAR: EVENTO_ACABAR, MUTEX_POSICION_ADELANTE, MUTEX_POSICION_CAMBIO_DE_CARRIL

						  //Añadimos el evento acabar para detenernos y no avanzar mas*/
	posiciones[0] = IPC.evento_acabar;

	/*Vemos si estamos en alguna de las 4 posiciones especiales para compartir los mutex*/
	if (apos + 1 != traductor(apos + 1, acarril))
		posiciones[1] = IPC.posiciones[traductor(apos + 1, acarril)];
	else if (apos != 136) //Si no estamos en la posicion 136 solicitamos el mutex de la posicion siguiente
		posiciones[1] = IPC.posiciones[apos + acarril * 137 + 1];
	else
		posiciones[1] = IPC.posiciones[acarril * 137]; //Si estamos en la posicion 136 solicitamos el mutex de la primera posicion

													   //Añadimos el evento cambio de carril si procede
	if (cambio(apos, acarril, &tpos, &tcarril))
	{
		posiciones[2] = IPC.posiciones[tpos + tcarril * 137];
		valor_devuelto = WaitForMultipleObjectsEx(3, posiciones, FALSE, INFINITE, TRUE);
	}
	else
		valor_devuelto = WaitForMultipleObjectsEx(2, posiciones, FALSE, INFINITE, TRUE);

	switch (valor_devuelto)
	{
	case WAIT_OBJECT_0 + 0:
		ExitThread(7);
		break;
	case WAIT_OBJECT_0 + 1:
		DLL.avanza_coche(carril, posicion, color);
		break;
	case WAIT_OBJECT_0 + 2:
		DLL.cambio_carril(carril, posicion, color);
		break;
	}

	/*Si estamos en alguna posicion con mutex compartido lo liberamos llamando a traductor*/
	if (traductor(apos, acarril) != apos)
		ReleaseMutex(IPC.posiciones[traductor(apos, acarril)]);
	else
		ReleaseMutex(IPC.posiciones[apos + acarril * 137]);
}
Exemplo n.º 6
0
static DWORD vlc_WaitForMultipleObjects (DWORD count, const HANDLE *handles,
        DWORD delay)
{
    DWORD ret;
    if (count == 0)
    {
#if VLC_WINSTORE_APP
        do {
            DWORD new_delay = 50;
            if (new_delay > delay)
                new_delay = delay;
            ret = SleepEx (new_delay, TRUE);
            if (delay != INFINITE)
                delay -= new_delay;
            if (isCancelled())
                ret = WAIT_IO_COMPLETION;
        } while (delay && ret == 0);
#else
        ret = SleepEx (delay, TRUE);
#endif

        if (ret == 0)
            ret = WAIT_TIMEOUT;
    }
    else {
#if VLC_WINSTORE_APP
        do {
            DWORD new_delay = 50;
            if (new_delay > delay)
                new_delay = delay;
            ret = WaitForMultipleObjectsEx (count, handles, FALSE, new_delay, TRUE);
            if (delay != INFINITE)
                delay -= new_delay;
            if (isCancelled())
                ret = WAIT_IO_COMPLETION;
        } while (delay && ret == WAIT_TIMEOUT);
#else
        ret = WaitForMultipleObjectsEx (count, handles, FALSE, delay, TRUE);
#endif
    }

    /* We do not abandon objects... this would be a bug */
    assert (ret < WAIT_ABANDONED_0 || WAIT_ABANDONED_0 + count - 1 < ret);

    if (unlikely(ret == WAIT_FAILED))
        abort (); /* We are screwed! */
    return ret;
}
Exemplo n.º 7
0
static DWORD WINAPI FileWatcherThread(void* param) {
    UNUSED(param);
    HANDLE handles[1];
    // must be alertable to receive ReadDirectoryChangesW() callbacks and APCs
    BOOL alertable = TRUE;

    for (;;) {
        handles[0] = g_threadControlHandle;
        DWORD timeout = GetTimeoutInMs();
        DWORD obj = WaitForMultipleObjectsEx(1, handles, FALSE, timeout, alertable);
        if (WAIT_TIMEOUT == obj) {
            RunManualChecks();
            continue;
        }

        if (WAIT_IO_COMPLETION == obj) {
            // APC complete. Nothing to do
            lf("FileWatcherThread(): APC complete");
            continue;
        }

        int n = (int)(obj - WAIT_OBJECT_0);

        if (n == 0) {
            // a thread was explicitly awaken
            ResetEvent(g_threadControlHandle);
            lf("FileWatcherThread(): g_threadControlHandle signalled");
        } else {
            dbglog::CrashLogF("FileWatcherThread(): n=%d", n);
            CrashIf(true);
        }
    }
}
Exemplo n.º 8
0
int PltWaitForEvent(PLT_EVENT* event) {
#if defined(LC_WINDOWS)
    DWORD error;
    HANDLE objects[2];

    objects[0] = *event;
    objects[1] = findCurrentThread()->termRequested;
    error = WaitForMultipleObjectsEx(2, objects, FALSE, INFINITE, FALSE);
    if (error == WAIT_OBJECT_0) {
        return PLT_WAIT_SUCCESS;
    }
    else if (error == WAIT_OBJECT_0 + 1) {
        return PLT_WAIT_INTERRUPTED;
    }
    else {
        LC_ASSERT(0);
        return -1;
    }
#else
    pthread_mutex_lock(&event->mutex);
    while (!event->signalled) {
        pthread_cond_wait(&event->cond, &event->mutex);
    }
    pthread_mutex_unlock(&event->mutex);
    
    return PLT_WAIT_SUCCESS;
#endif
}
Exemplo n.º 9
0
    bool BackgroundJobProcessor::WaitWithThread(ParallelThreadData *parallelThreadData, const Event &e, const unsigned int milliseconds)
    {
        const HANDLE handles[] = { e.Handle(), parallelThreadData->threadHandle };

        // If we have a thread service, then only wait on the event, not the actual thread handle.
        DWORD handleCount = 2;
        if (threadService->HasCallback())
        {
            handleCount = 1;
        }

        const unsigned int result = WaitForMultipleObjectsEx(handleCount, handles, false, milliseconds, false);

        if (!(result == WAIT_OBJECT_0 || result == WAIT_OBJECT_0 + 1 || (result == WAIT_TIMEOUT && milliseconds != INFINITE)))
        {
            Js::Throw::FatalInternalError();
        }

        if (result == WAIT_OBJECT_0 + 1)
        {
            // Apparently, sometimes the thread dies while waiting for an event. It should only be during process shutdown but
            // we can't know because DLL_PROCESS_DETACH may not have been called yet, which is bizarre. It seems unclear why
            // this happens and this could cause unpredictable behavior since the behavior of this object is undefined if the
            // thread is killed arbitrarily, or if there are incoming calls after Close. In any case, uses of this function have
            // been ported from BackgroundCodeGenThread. For now, we assume that Close will be called eventually and set the
            // state to what it should be before Close is called.
            parallelThreadData->isWaitingForJobs = false;
        }

        return result == WAIT_OBJECT_0;

    }
Exemplo n.º 10
0
int w_poll_events(struct watchman_event_poll *p, int n, int timeoutms) {
  HANDLE handles[MAXIMUM_WAIT_OBJECTS];
  int i;
  DWORD res;

  if (n > MAXIMUM_WAIT_OBJECTS - 1) {
    // Programmer error :-/
    w_log(W_LOG_FATAL, "%d > MAXIMUM_WAIT_OBJECTS-1 (%d)\n", n,
        MAXIMUM_WAIT_OBJECTS - 1);
  }

  for (i = 0; i < n; i++) {
    handles[i] = p[i].evt;
    p[i].ready = false;
  }

  res = WaitForMultipleObjectsEx(n, handles, false, timeoutms, true);

  if (res == WAIT_FAILED) {
    errno = map_win32_err(GetLastError());
    return -1;
  }
  // Note: WAIT_OBJECT_0 == 0
  if (/* res >= WAIT_OBJECT_0 && */ res < WAIT_OBJECT_0 + n) {
    p[res - WAIT_OBJECT_0].ready = true;
    return 1;
  }
  if (res >= WAIT_ABANDONED_0 && res < WAIT_ABANDONED_0 + n) {
    p[res - WAIT_ABANDONED_0].ready = true;
    return 1;
  }
  return 0;
}
Exemplo n.º 11
0
DWORD OutputMonitor::__ProcessImpl()
{
    DWORD dret;
    int ret;
    HANDLE hWaitHandle[2];

    hWaitHandle[0] = this->m_hDBWinDataReady;
    hWaitHandle[1] = this->m_ThreadControl.exitevt;

    /*make sure buffer ready for client handle*/
    SetEvent(this->m_hDBWinBufferReady);

    while(this->m_ThreadControl.running) {
        dret = WaitForMultipleObjectsEx(2,hWaitHandle,FALSE,INFINITE,TRUE);
        if(dret == WAIT_OBJECT_0) {
            ret = this->__HandleBufferIn();
            if(ret < 0) {
                ret = GETERRNO();
                dret = -ret;
                goto out;
            }
        } else if(dret == WAIT_FAILED || dret == WAIT_ABANDONED) {
            ret = GETERRNO();
            dret = -ret;
            goto out;
        }
    }

    ret = 0;

out:
    this->m_ThreadControl.exited = 1;
    SETERRNO(ret);
    return dret;
}
Exemplo n.º 12
0
/* Entry Point for child thread. */
DWORD PALAPI WaiterProc(LPVOID lpParameter)
{
    HANDLE Semaphore;
    DWORD OldTickCount;
    DWORD NewTickCount;
    BOOL Alertable;
    DWORD ret;

    /* Create a semaphore that is not in the signalled state */
    Semaphore = CreateSemaphoreW(NULL, 0, 1, NULL);

    if (Semaphore == NULL)
    {
        Fail("Failed to create semaphore!  GetLastError returned %d.\n",
            GetLastError());
    }

    Alertable = (BOOL) lpParameter;

    OldTickCount = GetTickCount();

    ret = WaitForMultipleObjectsEx(1, &Semaphore, FALSE, ChildThreadWaitTime, 
        Alertable);
    
    NewTickCount = GetTickCount();


    if (Alertable && ret != WAIT_IO_COMPLETION)
    {
        Fail("Expected the interrupted wait to return WAIT_IO_COMPLETION.\n"
            "Got %d\n", ret);
    }
    else if (!Alertable && ret != WAIT_TIMEOUT)
    {
        Fail("WaitForMultipleObjectsEx did not timeout.\n"
            "Expected return of WAIT_TIMEOUT, got %d.\n", ret);
    }


    /* 
    * Check for DWORD wraparound
    */
    if (OldTickCount>NewTickCount)
    {
        OldTickCount -= NewTickCount+1;
        NewTickCount  = 0xFFFFFFFF;
    }

    ThreadWaitDelta = NewTickCount - OldTickCount;

    ret = CloseHandle(Semaphore);
    if (!ret)
    {
        Fail("Unable to close handle to semaphore!\n"
            "GetLastError returned %d\n", GetLastError());
    }

    return 0;
}
    /// <summary>
    ///     Wait for new work
    /// </summary>
    UMSThreadProxy * TransmogrifiedPrimary::WaitForWork()
    {
        // 
        // There are 3 possibilities here
        // 1. A proxy needs to be polled for execution
        // 2. A proxy needs to be transmogrified/retired/run to thread main
        // 3. This background thread needs to be retired
        //
        const int maxCount = 3;
        HANDLE hObjects[maxCount];
        int count = 0;
        hObjects[count++] = m_poller.GetEvent();
        hObjects[count++] = m_hBlock;
        hObjects[count++] = m_hRetire;

        CONCRT_COREASSERT(count == maxCount);       

        DWORD timeout = INFINITE;

        for(;;)
        {
            DWORD result = WaitForMultipleObjectsEx(count, hObjects, FALSE, timeout, FALSE);
            DWORD index = (result == WAIT_TIMEOUT) ? 0 : (result - WAIT_OBJECT_0);

            if (index == 0)
            {
                bool done = m_poller.DoPolling();
                
                //
                // Poll every interval
                //
                timeout = done ? INFINITE : UMSBackgroundPoller::PollInterval();
            }
            else if (index == 1)
            {
                //
                // Dequeue new work and bind it to the primary. It is possible
                // that we already picked up the entry that signalled the event.
                //
                m_pBoundProxy = m_queuedExecutions.Dequeue();
                if (m_pBoundProxy != NULL)
                {
                    return m_pBoundProxy;
                }
            }
            else
            {
                // 
                // Canceled
                //
                CONCRT_COREASSERT(index == 2);

                CONCRT_COREASSERT(m_queueCount == 0);
                CONCRT_COREASSERT(timeout == INFINITE);
                return NULL;
            }
        }
    }
Exemplo n.º 14
0
/*
 * PGSemaphoreLock
 *
 * Lock a semaphore (decrement count), blocking if count would be < 0.
 * Serve the interrupt if interruptOK is true.
 */
void
PGSemaphoreLock(PGSemaphore sema)
{
	HANDLE		wh[2];
	bool		done = false;

	/*
	 * Note: pgwin32_signal_event should be first to ensure that it will be
	 * reported when multiple events are set.  We want to guarantee that
	 * pending signals are serviced.
	 */
	wh[0] = pgwin32_signal_event;
	wh[1] = *sema;

	/*
	 * As in other implementations of PGSemaphoreLock, we need to check for
	 * cancel/die interrupts each time through the loop.  But here, there is
	 * no hidden magic about whether the syscall will internally service a
	 * signal --- we do that ourselves.
	 */
	while (!done)
	{
		DWORD		rc;

		CHECK_FOR_INTERRUPTS();

		rc = WaitForMultipleObjectsEx(2, wh, FALSE, INFINITE, TRUE);
		switch (rc)
		{
			case WAIT_OBJECT_0:
				/* Signal event is set - we have a signal to deliver */
				pgwin32_dispatch_queued_signals();
				break;
			case WAIT_OBJECT_0 + 1:
				/* We got it! */
				done = true;
				break;
			case WAIT_IO_COMPLETION:

				/*
				 * The system interrupted the wait to execute an I/O
				 * completion routine or asynchronous procedure call in this
				 * thread.  PostgreSQL does not provoke either of these, but
				 * atypical loaded DLLs or even other processes might do so.
				 * Now, resume waiting.
				 */
				break;
			case WAIT_FAILED:
				ereport(FATAL,
						(errmsg("could not lock semaphore: error code %lu",
								GetLastError())));
				break;
			default:
				elog(FATAL, "unexpected return code from WaitForMultipleObjectsEx(): %lu", rc);
				break;
		}
	}
}
Exemplo n.º 15
0
DWORD
WaitForMultipleObjects(
    DWORD nCount,
    CONST HANDLE *lpHandles,
    BOOL bWaitAll,
    DWORD dwMilliseconds
)

/*++

Routine Description:

A wait operation on multiple waitable objects (up to
MAXIMUM_WAIT_OBJECTS) is accomplished with the WaitForMultipleObjects
function.

Arguments:

    nCount - A count of the number of objects that are to be waited on.

    lpHandles - An array of object handles.  Each handle must have
        SYNCHRONIZE access to the associated object.

    bWaitAll - A flag that supplies the wait type.  A value of TRUE
        indicates a "wait all".  A value of false indicates a "wait
        any".

    dwMilliseconds - A time-out value that specifies the relative time,
        in milliseconds, over which the wait is to be completed.  A
        timeout value of 0 specified that the wait is to timeout
        immediately.  This allows an application to test an object to
        determine if it is in the signaled state.  A timeout value of -1
        specifies an infinite timeout period.

Return Value:

    WAIT_TIME_OUT - indicates that the wait was terminated due to the
        TimeOut conditions.

    0 to MAXIMUM_WAIT_OBJECTS-1, indicates, in the case of wait for any
        object, the object number which satisfied the wait.  In the case
        of wait for all objects, the value only indicates that the wait
        was completed successfully.

    WAIT_ABANDONED_0 to (WAIT_ABANDONED_0)+(MAXIMUM_WAIT_OBJECTS - 1),
        indicates, in the case of wait for any object, the object number
        which satisfied the event, and that the object which satisfied
        the event was abandoned.  In the case of wait for all objects,
        the value indicates that the wait was completed successfully and
        at least one of the objects was abandoned.

--*/

{
    return WaitForMultipleObjectsEx(nCount,lpHandles,bWaitAll,dwMilliseconds,FALSE);
}
Exemplo n.º 16
0
MFMediaIOEx::ReadResult MFMediaIOEx::GetReadResult()
{
	HANDLE handles[] = {_hEventRead,_hEventCancel};
	DWORD result = WaitForMultipleObjectsEx(_countof(handles),handles,FALSE,_dwReadTimeout,FALSE);
	if (result == WAIT_TIMEOUT)
		return ReadTimeout;
	else if (result == WAIT_FAILED)
		return ReadFailed;
	return result == 0 ? ReadOK:ReadCancel;
}
Exemplo n.º 17
0
bool AsyncEvents::wait(bool all, int ms)
{
	int result = WaitForMultipleObjectsEx(m_count, &handle(0), all, ms, true);
	if (result == WAIT_IO_COMPLETION)
		return false;

	m_activated = result - WAIT_OBJECT_0;

	return true;
}
Exemplo n.º 18
0
/***********************************************************************
 *           WaitForMultipleObjectsEx   (KERNEL.495)
 */
DWORD WINAPI WaitForMultipleObjectsEx16( DWORD count, const HANDLE *handles,
                                         BOOL wait_all, DWORD timeout, BOOL alertable )
{
    DWORD retval, mutex_count;

    ReleaseThunkLock( &mutex_count );
    retval = WaitForMultipleObjectsEx( count, handles, wait_all, timeout, alertable );
    RestoreThunkLock( mutex_count );
    return retval;
}
Exemplo n.º 19
0
static void wait_for_any_event(struct resman *rman)
{
	unsigned int num_handles;

	if(!(num_handles = dynarr_size(rman->wait_handles))) {
		return;
	}

	WaitForMultipleObjectsEx(num_handles, rman->wait_handles, FALSE, INFINITE, TRUE);
}
Exemplo n.º 20
0
/* Entry Point for child thread. */
DWORD PALAPI WaiterProc(LPVOID lpParameter)
{
    HANDLE Semaphore;
    UINT64 OldTimeStamp;
    UINT64 NewTimeStamp;
    BOOL Alertable;
    DWORD ret;

    /* Create a semaphore that is not in the signalled state */
    Semaphore = CreateSemaphoreW(NULL, 0, 1, NULL);

    if (Semaphore == NULL)
    {
        Fail("Failed to create semaphore!  GetLastError returned %d.\n",
            GetLastError());
    }

    Alertable = (BOOL) lpParameter;

    LARGE_INTEGER performanceFrequency;
    if (!QueryPerformanceFrequency(&performanceFrequency))
    {
        Fail("Failed to query performance frequency!");
    }

    OldTimeStamp = GetHighPrecisionTimeStamp(performanceFrequency);

    ret = WaitForMultipleObjectsEx(1, &Semaphore, FALSE, ChildThreadWaitTime, 
        Alertable);
    
    NewTimeStamp = GetHighPrecisionTimeStamp(performanceFrequency);


    if (Alertable && ret != WAIT_IO_COMPLETION)
    {
        Fail("Expected the interrupted wait to return WAIT_IO_COMPLETION.\n"
            "Got %d\n", ret);
    }
    else if (!Alertable && ret != WAIT_TIMEOUT)
    {
        Fail("WaitForMultipleObjectsEx did not timeout.\n"
            "Expected return of WAIT_TIMEOUT, got %d.\n", ret);
    }

    ThreadWaitDelta = NewTimeStamp - OldTimeStamp;

    ret = CloseHandle(Semaphore);
    if (!ret)
    {
        Fail("Unable to close handle to semaphore!\n"
            "GetLastError returned %d\n", GetLastError());
    }

    return 0;
}
Exemplo n.º 21
0
int __cdecl main( int argc, char **argv)
{
    HANDLE Mutex;
    HANDLE hThread = 0;
    DWORD dwThreadId = 0;
    int ret;

    if (0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }

    Mutex = CreateMutexW(NULL, FALSE, NULL);
    if (Mutex == NULL)
    {
        Fail("Unable to create the mutex.  GetLastError returned %d\n",
             GetLastError());
    }

    hThread = CreateThread( NULL,
                            0,
                            (LPTHREAD_START_ROUTINE)AcquiringProc,
                            (LPVOID) Mutex,
                            0,
                            &dwThreadId);

    if (hThread == NULL)
    {
        Fail("ERROR: Was not able to create the thread to test!\n"
             "GetLastError returned %d\n", GetLastError());
    }

    Sleep(ParentDelayTime);

    ret = WaitForMultipleObjectsEx(1, &Mutex, FALSE, INFINITE, FALSE);
    if (ret != WAIT_OBJECT_0)
    {
        Fail("Expected WaitForMultipleObjectsEx to return WAIT_OBJECT_0\n"
             "Got %d\n", ret);
    }

    if (!CloseHandle(Mutex))
    {
        Fail("CloseHandle on the mutex failed!\n");
    }

    if (!CloseHandle(hThread))
    {
        Fail("CloseHandle on the thread failed!\n");
    }

    PAL_Terminate();
    return PASS;
}
Exemplo n.º 22
0
static int rpcrt4_protseq_np_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
{
    HANDLE b_handle;
    HANDLE *objs = wait_array;
    DWORD res;
    RpcConnection *cconn;
    RpcConnection_np *conn;
    
    if (!objs)
        return -1;

    do
    {
        /* an alertable wait isn't strictly necessary, but due to our
         * overlapped I/O implementation in Wine we need to free some memory
         * by the file user APC being called, even if no completion routine was
         * specified at the time of starting the async operation */
        res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
    } while (res == WAIT_IO_COMPLETION);

    if (res == WAIT_OBJECT_0)
        return 0;
    else if (res == WAIT_FAILED)
    {
        ERR("wait failed with error %d\n", GetLastError());
        return -1;
    }
    else
    {
        b_handle = objs[res - WAIT_OBJECT_0];
        /* find which connection got a RPC */
        EnterCriticalSection(&protseq->cs);
        conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
        while (conn) {
            if (b_handle == conn->ovl.hEvent) break;
            conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
        }
        cconn = NULL;
        if (conn)
            RPCRT4_SpawnConnection(&cconn, &conn->common);
        else
            ERR("failed to locate connection for handle %p\n", b_handle);
        LeaveCriticalSection(&protseq->cs);
        if (cconn)
        {
            RPCRT4_new_client(cconn);
            return 1;
        }
        else return -1;
    }
}
Exemplo n.º 23
0
CAMLprim value win_wait (value timeout, value event_count) {
  CAMLparam2(timeout, event_count);
  DWORD t, t2;
  DWORD res;
  long ret, n = Long_val(event_count);
  t = Long_val(timeout);
  if (t < 0) t = INFINITE;
  t2 = (compN > 0) ? 0 : t;
  D(printf("Waiting: %ld events, timeout %ldms -> %ldms\n", n, t, t2));
  res =
    (n > 0) ?
    WaitForMultipleObjectsEx(n, events, FALSE, t, TRUE) :
    WaitForMultipleObjectsEx(1, &dummyEvent, FALSE, t, TRUE);
  D(printf("Done waiting\n"));
  if ((t != t2) && (res == WAIT_TIMEOUT)) res = WAIT_IO_COMPLETION;
  switch (res) {
  case WAIT_TIMEOUT:
    D(printf("Timeout\n"));
    ret = -1;
    break;
  case WAIT_IO_COMPLETION:
    D(printf("I/O completion\n"));
    ret = -2;
    break;
  case WAIT_FAILED:
    D(printf("Wait failed\n"));
    ret = 0;
    win32_maperr (GetLastError ());
    uerror("WaitForMultipleObjectsEx", Nothing);
    break;
  default:
    ret = res;
    D(printf("Event: %ld\n", res));
    break;
  }
  get_queue (Val_unit);
  CAMLreturn (Val_long(ret));
}
Exemplo n.º 24
0
DWORD pymWaitForMultipleObjectsEx(DWORD nCount, HANDLE* lpHandles, BOOL bWaitAll, DWORD dwMilliseconds, BOOL bAlertable) {
	PyMFC_PROLOGUE(pymShellExecute);
	{
		PyMFCLeavePython lp;
		DWORD ret = WaitForMultipleObjectsEx(nCount, lpHandles, bWaitAll, dwMilliseconds, bAlertable);

		if (ret == WAIT_FAILED) {
			throw PyMFC_WIN32ERR();
		}

		return ret;
	}
	PyMFC_EPILOGUE(0);
}
Exemplo n.º 25
0
/*
 * @implemented
 */
DWORD
WINAPI
WaitForMultipleObjects(IN DWORD nCount,
                       IN CONST HANDLE *lpHandles,
                       IN BOOL bWaitAll,
                       IN DWORD dwMilliseconds)
{
    /* Call the extended API */
    return WaitForMultipleObjectsEx(nCount,
                                    lpHandles,
                                    bWaitAll,
                                    dwMilliseconds,
                                    FALSE);
}
Exemplo n.º 26
0
/******************************************************************************
 *                                                                            *
 * Function: zbx_free_service_resources                                       *
 *                                                                            *
 * Purpose: free service resources allocated by main thread                   *
 *                                                                            *
 ******************************************************************************/
void	zbx_free_service_resources(void)
{
	if (NULL != threads)
	{
		int		i;
#if !defined(_WINDOWS)
		sigset_t	set;

		/* ignore SIGCHLD signals in order for zbx_sleep() to work */
		sigemptyset(&set);
		sigaddset(&set, SIGCHLD);
		sigprocmask(SIG_BLOCK, &set, NULL);
#else
		/* wait for threads to finish first. although listener threads will never end */
		WaitForMultipleObjectsEx(threads_num, threads, TRUE, 1000, FALSE);
#endif
		for (i = 0; i < threads_num; i++)
		{
			if (threads[i])
				zbx_thread_kill(threads[i]);
		}

		for (i = 0; i < threads_num; i++)
		{
			if (threads[i])
				zbx_thread_wait(threads[i]);

			threads[i] = ZBX_THREAD_HANDLE_NULL;
		}

		zbx_free(threads);
	}

	zabbix_log(LOG_LEVEL_INFORMATION, "Zabbix Agent stopped. Zabbix %s (revision %s).",
			ZABBIX_VERSION, ZABBIX_REVISION);

#ifndef _WINDOWS
	unload_modules();
#endif
	zabbix_close_log();

	free_metrics();
	alias_list_free();
	free_collector_data();
#ifdef _WINDOWS
	free_perf_collector();
	zbx_co_uninitialize();
#endif
}
Exemplo n.º 27
0
/*
 * PGSemaphoreLock
 *
 * Lock a semaphore (decrement count), blocking if count would be < 0.
 * Serve the interrupt if interruptOK is true.
 */
void
PGSemaphoreLock(PGSemaphore sema, bool interruptOK)
{
	DWORD		ret;
	HANDLE		wh[2];

	/*
	 * Note: pgwin32_signal_event should be first to ensure that it will be
	 * reported when multiple events are set.  We want to guarantee that
	 * pending signals are serviced.
	 */
	wh[0] = pgwin32_signal_event;
	wh[1] = *sema;

	/*
	 * As in other implementations of PGSemaphoreLock, we need to check for
	 * cancel/die interrupts each time through the loop.  But here, there is
	 * no hidden magic about whether the syscall will internally service a
	 * signal --- we do that ourselves.
	 */
	do
	{
		ImmediateInterruptOK = interruptOK;
		CHECK_FOR_INTERRUPTS();

		ret = WaitForMultipleObjectsEx(2, wh, FALSE, INFINITE, TRUE);

		if (ret == WAIT_OBJECT_0)
		{
			/* Signal event is set - we have a signal to deliver */
			pgwin32_dispatch_queued_signals();
			errno = EINTR;
		}
		else if (ret == WAIT_OBJECT_0 + 1)
		{
			/* We got it! */
			errno = 0;
		}
		else
			/* Otherwise we are in trouble */
			errno = EIDRM;

		ImmediateInterruptOK = false;
	} while (errno == EINTR);

	if (errno != 0)
		ereport(FATAL,
				(errmsg("could not lock semaphore: error code %lu", GetLastError())));
}
    /// <summary>
    ///     Wait for a proxy to appear on the completion list
    /// </summary>
    UMSThreadProxy * TransmogrifiedPrimary::WaitForBlockedThread(UMSThreadProxy * pProxy)
    {
        //
        // While waiting on the completion list we need to poll proxies for execution, if any.
        // This is required because the current proxy could be blocked for a resource that is
        // held by a UT that is suspended (and needs to be polled for subsequent execution).
        //
        const int maxCount = 2;
        HANDLE hObjects[maxCount];
        int count = 0;
        hObjects[count++] = m_poller.GetEvent();
        hObjects[count++] = m_hCompletionListEvent;
        
        CONCRT_COREASSERT(count == maxCount);

        DWORD timeout = INFINITE;

        for(;;)
        {
            DWORD result = WaitForMultipleObjectsEx(count, hObjects, FALSE, timeout, FALSE);
            DWORD index = (result == WAIT_TIMEOUT) ? 0 : (result - WAIT_OBJECT_0);

            if (index == 0)
            {
                bool done = m_poller.DoPolling();

                //
                // Poll every interval
                //
                timeout = done ? INFINITE : UMSBackgroundPoller::PollInterval();
            }
            else
            {
                CONCRT_COREASSERT(index == 1);

                // Proxy came back on the completion list
                PUMS_CONTEXT pUMSContext = NULL;
                if (!UMS::DequeueUmsCompletionListItems(m_pCompletionList, 0, &pUMSContext))
                    throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));

                //
                // The completed thread should be the one we are running
                //
                UMSThreadProxy *pCompletedProxy = UMSThreadProxy::FromUMSContext(pUMSContext);
                CONCRT_COREASSERT(pCompletedProxy == pProxy && UMS::GetNextUmsListItem(pUMSContext) == NULL);
                return pCompletedProxy;
            }
        }
    }
Exemplo n.º 29
0
/*
 * @implemented
 */
DWORD
WSAAPI
WSAWaitForMultipleEvents(IN DWORD cEvents,
                         IN CONST WSAEVENT FAR* lphEvents,
                         IN BOOL fWaitAll,
                         IN DWORD dwTimeout,
                         IN BOOL fAlertable)
{
    /* Call Win32 */
    return WaitForMultipleObjectsEx(cEvents, 
                                    lphEvents, 
                                    fWaitAll, 
                                    dwTimeout, 
                                    fAlertable);
}
Exemplo n.º 30
0
void __cdecl main(int argc, char **argv)
{
    getargs(&argc, &argv);
    if (argc < 2) return;

    DWORD    dwMaxThread, dwExitCode, dwCount = 0, dwTotal = 0;
    LPHANDLE phThread;
    SYSTEM_INFO si;
    LARGE_INTEGER lFrequency, lStopCounter, lStartCounter;

    GetSystemInfo(&si);
    dwMaxThread = si.dwNumberOfProcessors << 1;
    g_hSemaphore = CreateSemaphore(NULL, 1, dwMaxThread, NULL);
    if (g_hSemaphore == NULL)
    {
        printf("CreateSemaphore() failed.\n");
    }
    else
    {
        QueryPerformanceFrequency(&lFrequency);
        QueryPerformanceCounter(&lStartCounter);
        hHeap = GetProcessHeap();
        ExtractDict(pbDict);
        phThread = (LPHANDLE)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, (argc - 1) * sizeof(*phThread));
        for (DWORD i = 0; i != argc - 1; ++i)
            phThread[i] = CreateThread(NULL, 0, Import, (LPVOID)argv[i + 1], 0, NULL);

        WaitForMultipleObjectsEx(argc - 1, phThread, TRUE, INFINITE, FALSE);
        for (DWORD i = 0; i != argc - 1; ++i)
        {
            GetExitCodeThread(phThread[i], &dwExitCode);
            dwCount += dwExitCode;
        }

        for (char i = 0; i != countof(Array_of_Data); ++i)
        {
            HeapFree(hHeap, 0, pbDict[i]);
        }

        CloseHandle(g_hSemaphore);
        QueryPerformanceCounter(&lStopCounter);
        printf("Success: %d\n"
               "Elapsed time: %lf ms\n",
               dwCount,
               (lStopCounter.QuadPart - lStartCounter.QuadPart) * 1000.0 / lFrequency.QuadPart);
    }
}