Ejemplo n.º 1
0
static void test_semaphore(void)
{
    HANDLE handle, handle2;

    /* test case sensitivity */

    SetLastError(0xdeadbeef);
    handle = CreateSemaphoreA(NULL, 0, 1, __FILE__ ": Test Semaphore");
    ok(handle != NULL, "CreateSemaphore failed with error %u\n", GetLastError());
    ok(GetLastError() == 0, "wrong error %u\n", GetLastError());

    SetLastError(0xdeadbeef);
    handle2 = CreateSemaphoreA(NULL, 0, 1, __FILE__ ": Test Semaphore");
    ok( handle2 != NULL, "CreateSemaphore failed with error %d\n", GetLastError());
    ok( GetLastError() == ERROR_ALREADY_EXISTS, "wrong error %u\n", GetLastError());
    CloseHandle( handle2 );

    SetLastError(0xdeadbeef);
    handle2 = CreateSemaphoreA(NULL, 0, 1, __FILE__ ": TEST SEMAPHORE");
    ok( handle2 != NULL, "CreateSemaphore failed with error %d\n", GetLastError());
    ok( GetLastError() == 0, "wrong error %u\n", GetLastError());
    CloseHandle( handle2 );

    SetLastError(0xdeadbeef);
    handle2 = OpenSemaphoreA( SEMAPHORE_ALL_ACCESS, FALSE, __FILE__ ": Test Semaphore");
    ok( handle2 != NULL, "OpenSemaphore failed with error %d\n", GetLastError());
    CloseHandle( handle2 );

    SetLastError(0xdeadbeef);
    handle2 = OpenSemaphoreA( SEMAPHORE_ALL_ACCESS, FALSE, __FILE__ ": TEST SEMAPHORE");
    ok( !handle2, "OpenSemaphore succeeded\n");
    ok( GetLastError() == ERROR_FILE_NOT_FOUND, "wrong error %u\n", GetLastError());

    CloseHandle( handle );
}
Ejemplo n.º 2
0
void dgThreads::CreateThreaded(dgInt32 threads)
{
  if (m_numOfThreads)
  {
    DestroydgThreads();
  }

#ifdef _WIN32
  if ((threads > 1) && (m_numberOfCPUCores > 1))
  {
    m_numOfThreads = GetMin(threads, m_numberOfCPUCores);

    m_emptySlot = CreateSemaphoreA(NULL, DG_MAXQUEUE, DG_MAXQUEUE, NULL);
    m_workToDo = CreateSemaphoreA(NULL, 0, DG_MAXQUEUE, NULL);
    m_exit = CreateEventA(NULL, TRUE, FALSE, NULL);

    InitializeCriticalSection(&m_criticalSection);

    m_topIndex = 0;
    m_bottomIndex = 0;
    m_workInProgress = 0;
    for (dgInt32 i = 0; i < m_numOfThreads; i++)
    {
      m_threadhandles[i] = (HANDLE) _beginthreadex(NULL, 0, ThreadExecute,
          &m_localData[i], 0, NULL);
    }
  }
#else
  if ((threads > 1) && (m_numberOfCPUCores > 1))
  {
#ifdef TARGET_OS_IPHONE
    m_numOfThreads = 0;
#else
    m_numOfThreads = (threads<m_numberOfCPUCores ? threads : m_numberOfCPUCores);
#endif

    m_emptySlot = DG_MAXQUEUE;
    m_workToDo = 0;
    m_workToDoSpinLock = 0;
    m_exit = false;
    m_criticalSection = 0;

    m_topIndex = 0;
    m_bottomIndex = 0;
    m_workInProgress = 0;

#ifndef TARGET_OS_IPHONE
    for(dgInt32 i=0; i < m_numOfThreads; i++)
    {
      pthread_create( &m_threadhandles[i], NULL, ThreadExecute, &m_localData[i]);
    }
#endif
  }
#endif
}
Ejemplo n.º 3
0
BOOL install_wine_gecko(BOOL silent)
{
    HANDLE hsem;

    SetLastError(ERROR_SUCCESS);
    hsem = CreateSemaphoreA( NULL, 0, 1, "mshtml_install_semaphore");

    if(GetLastError() == ERROR_ALREADY_EXISTS) {
        WaitForSingleObject(hsem, INFINITE);
    }else {
        /*
         * Try to find Gecko .cab file in following order:
         * - directory stored in GeckoCabDir value of HKCU/Software/MSHTML key
         * - $datadir/gecko
         * - download from URL stored in GeckoUrl value of HKCU/Software/MSHTML key
         */
        if(!install_from_registered_dir()
           && !install_from_default_dir()
           && !silent && (url = get_url()))
            DialogBoxW(hInst, MAKEINTRESOURCEW(ID_DWL_DIALOG), 0, installer_proc);
    }

    ReleaseSemaphore(hsem, 1, NULL);
    CloseHandle(hsem);

    return TRUE;
}
Ejemplo n.º 4
0
static void windows_exit(struct libusb_context *ctx)
{
	HANDLE semaphore;
	char sem_name[11 + 8 + 1]; // strlen("libusb_init") + (32-bit hex PID) + '\0'
	UNUSED(ctx);

	sprintf(sem_name, "libusb_init%08X", (unsigned int)(GetCurrentProcessId() & 0xFFFFFFFF));
	semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
	if (semaphore == NULL)
		return;

	// A successful wait brings our semaphore count to 0 (unsignaled)
	// => any concurent wait stalls until the semaphore release
	if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
		CloseHandle(semaphore);
		return;
	}

	// Only works if exits and inits are balanced exactly
	if (--init_count == 0) { // Last exit
		if (usbdk_available) {
			usbdk_backend.exit(ctx);
			usbdk_available = false;
		}
		winusb_backend.exit(ctx);
		htab_destroy();
		windows_destroy_clock();
		windows_exit_dlls();
	}

	ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
	CloseHandle(semaphore);
}
Ejemplo n.º 5
0
 semaphore::semaphore(int32 initialCount, int32 maximumCount, const char *pName)
 {
     m_handle = CreateSemaphoreA(NULL, initialCount, maximumCount, pName);
     if (NULL == m_handle)
     {
         VOGL_FAIL("semaphore: CreateSemaphore() failed");
     }
 }
Ejemplo n.º 6
0
	Semaphore::Semaphore()
	{
#if BX_PLATFORM_XBOXONE || BX_PLATFORM_WINRT
		m_handle = CreateSemaphoreExW(NULL, 0, LONG_MAX, NULL, 0, SEMAPHORE_ALL_ACCESS);
#else
		m_handle = CreateSemaphoreA(NULL, 0, LONG_MAX, NULL);
#endif
		BX_CHECK(NULL != m_handle, "Failed to create Semaphore!");
	}
Ejemplo n.º 7
0
            inline handle create_anonymous_semaphore_nothrow(long initial_count,long max_count)
            {
#if !defined(BOOST_NO_ANSI_APIS)
                handle const res=CreateSemaphoreA(0,initial_count,max_count,0);
#else
                handle const res=CreateSemaphoreW(0,initial_count,max_count,0);
#endif
                return res;
            }
Ejemplo n.º 8
0
HOOKFUNC HANDLE WINAPI MyCreateSemaphoreA(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes,LONG lInitialCount,LONG lMaximumCount,LPCSTR lpName)
{
	HANDLE rv = CreateSemaphoreA(lpSemaphoreAttributes, lInitialCount, lMaximumCount, lpName);
	debuglog(LCF_SYNCOBJ, __FUNCTION__ " returned 0x%X.\n", rv);
	EnterCriticalSection(&s_handleCS);
	std::set<HANDLE>& handles = s_threadIdHandles[GetCurrentThreadId()];
	handles.insert(rv);
	LeaveCriticalSection(&s_handleCS);
	return rv;
}
Ejemplo n.º 9
0
/* 信号量 */
SEM sem_Create(const char* name,unsigned int val){
#if defined(WIN32) || defined(_WIN64)
	return CreateSemaphoreA(NULL,val,INFINITE,name);
#else
	sem_t* sem = sem_open(name,O_CREAT,IPC_ALL_ACCESS,val);
	if(sem == SEM_FAILED)
		sem = NULL;
	return sem;
#endif
}
Ejemplo n.º 10
0
GSISemaphoreID gsiCreateSemaphore(gsi_i32 theInitialCount, gsi_i32 theMaxCount, char* theName)
{
	GSISemaphoreID aSemaphore = CreateSemaphoreA(NULL, theInitialCount, theMaxCount, theName);
	if (aSemaphore == NULL)
	{
		gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Misc, GSIDebugLevel_WarmError,
			"Failed to create semaphore\r\n");
	}
	return aSemaphore;
}
Ejemplo n.º 11
0
 HOOKFUNC HANDLE WINAPI MyCreateSemaphoreA(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, LONG lInitialCount, LONG lMaximumCount, LPCSTR lpName)
 {
     ENTER();
     HANDLE rv = CreateSemaphoreA(lpSemaphoreAttributes, lInitialCount, lMaximumCount, lpName);
     LEAVE(rv);
     EnterCriticalSection(&s_handleCS);
     std::set<HANDLE>& handles = s_threadIdHandles[GetCurrentThreadId()];
     handles.insert(rv);
     LeaveCriticalSection(&s_handleCS);
     return rv;
 }
Burger::Semaphore::Semaphore(Word32 uCount) :
	m_uCount(uCount)
{
	// Get the maximum semaphores
	Word32 uMax = uCount+32768U;
	// Did it wrap (Overflow?)
	if (uMax<uCount) {
		// Use max
		uMax = BURGER_MAXUINT;
	}
	m_pSemaphore = CreateSemaphoreA(NULL,uCount,uMax,NULL);
}
Ejemplo n.º 13
0
CSingleInstance::CSingleInstance(const string& strMutexName)
{
	// be sure to use a name that is unique for this application otherwise
	// two apps may think they are the same if they are using same name for
	// 3rd parm to CreateMutex
	SECURITY_ATTRIBUTES SA; 
	SECURITY_DESCRIPTOR SD;
	SECURITY_ATTRIBUTES *pSA = InitSecurityAttribute(SA, SD);
	//   Create   a   Semaphore   with   a   name   of   application   exename   
	m_hMutex = CreateSemaphoreA(pSA, 1, 1, strMutexName.c_str());
	m_dwLastError = ::GetLastError(); //save for use later...
}
Ejemplo n.º 14
0
            inline handle create_anonymous_semaphore(long initial_count,long max_count)
            {
#if !defined(BOOST_NO_ANSI_APIS)  
                handle const res=CreateSemaphoreA(0,initial_count,max_count,0);
#else
                handle const res=CreateSemaphoreW(0,initial_count,max_count,0);
#endif               
                if(!res)
                {
                    boost::throw_exception(thread_resource_error());
                }
                return res;
            }
Ejemplo n.º 15
0
msg_driven_service::msg_driven_service()
:m_semaphore(NULL),
m_hthread(NULL),
m_b_notify_exit(false),
m_timer(NULL),
m_ap_event_mgr(NULL)
{
	InitializeCriticalSection(&m_cs);
	m_semaphore=CreateSemaphoreA(NULL,0,1000,NULL);
	m_timer=CreateWaitableTimerA(NULL,FALSE,NULL);
	LARGE_INTEGER start_time;
	start_time.QuadPart=-1;
	SetWaitableTimer(m_timer,&start_time,1000,NULL,NULL,TRUE);
	m_ap_event_mgr.reset(new time_event_mgr);
}
Ejemplo n.º 16
0
int zsem_init(zsem_t* sem, int value){
  int ret = ZEOK;
#ifdef ZSYS_POSIX
  if(0 != (ret = sem_init(sem, 0, value))){
      ret = errno;
  }
#else//ZSYS_WINDOWS
  *sem = CreateSemaphoreA(NULL, value, ZSEM_MAX, NULL);
  if (NULL == *sem) {
	  ret = GetLastError();
  }
#endif
#if ZTRACE_SEM
  ZERRC(ret);
#endif
  return ret;
}
Ejemplo n.º 17
0
int am_agent_instance_init_init(int id) {
    int status = AM_ERROR;
#if defined(_WIN32)
    ic_sem = CreateSemaphoreA(NULL, 1, 1, get_global_name("Global\\"AM_CONFIG_INIT_NAME, id));
    if (ic_sem != NULL) {
        status = AM_SUCCESS;
    }
#elif defined(__APPLE__)
    kern_return_t rv = semaphore_create(mach_task_self(), &ic_sem, SYNC_POLICY_FIFO, 1);
    if (rv == KERN_SUCCESS) {
        status = AM_SUCCESS;
    }
#else
    ic_sem = sem_open(get_global_name(AM_CONFIG_INIT_NAME, id), O_CREAT, 0600, 1);
    if (ic_sem != SEM_FAILED) {
        status = AM_SUCCESS;
    }
#endif
    return status;
}
VCOS_STATUS_T
vcos_win32_named_semaphore_create(VCOS_NAMED_SEMAPHORE_T *sem, const char *name, VCOS_UNSIGNED count)
{
   char buf[64];
   HANDLE h;
   int ret = vcos_snprintf(buf, sizeof(buf), "Global\\%s", name);
   if (ret < 0)
   {
      vcos_assert(0);
      return VCOS_ENOSPC;
   }

   h = CreateSemaphoreA(NULL, count, 1<<16, buf);
   if (h != NULL)
   {
      sem->sem = h;
      return VCOS_SUCCESS;
   }
   else
      return vcos_win32_map_error();
}
Ejemplo n.º 19
0
zsem_t* zsem_create(int value){
  int ret = ZEOK;
  zsem_t* sem = (zsem_t*)malloc(sizeof(zsem_t));
  if(NULL != sem){
#ifdef ZSYS_POSIX
    if(0 != (ret = sem_init(sem, 0, value))){
      ret = errno;
    }
#else//ZSYS_WINDOWS
    *sem = CreateSemaphoreA(NULL, value, ZSEM_MAX, NULL);
    if (NULL == *sem) {
      ret = GetLastError();
    }
#endif
  }else{
    ret = ZEMEM_INSUFFICIENT;
  }
#if ZTRACE_SEM
  ZERRC(ret);
#endif
  return sem;
}
Ejemplo n.º 20
0
tb_semaphore_ref_t tb_semaphore_init(tb_size_t init)
{
    // check
    tb_assert_and_check_return_val(init <= TB_SEMAPHORE_VALUE_MAXN, tb_null);

    // done
    tb_bool_t               ok = tb_false;
    tb_semaphore_impl_t*    impl = tb_null;
    do
    {
        // make semaphore
        impl = tb_malloc0_type(tb_semaphore_impl_t);
        tb_assert_and_check_break(impl);

        // init semaphore 
        impl->semaphore = CreateSemaphoreA(tb_null, (DWORD)init, TB_SEMAPHORE_VALUE_MAXN, tb_null);
        tb_assert_and_check_break(impl->semaphore && impl->semaphore != INVALID_HANDLE_VALUE);

        // init value
        impl->value = init;

        // ok
        ok = tb_true;

    } while (0);

    // failed?
    if (!ok)
    {
        // exit it
        if (impl) tb_semaphore_exit((tb_semaphore_ref_t)impl);
        impl = tb_null;
    }

    // ok?
    return (tb_semaphore_ref_t)impl;
}
Ejemplo n.º 21
0
static pboolean
pp_cond_variable_init_xp (PCondVariable *cond)
{
	PCondVariableXP *cv_xp;

	if ((cond->cv = p_malloc0 (sizeof (PCondVariableXP))) == NULL) {
		P_ERROR ("PCondVariable::pp_cond_variable_init_xp: failed to allocate memory (internal)");
		return FALSE;
	}

	cv_xp = ((PCondVariableXP *) cond->cv);

	cv_xp->waiters_count = 0;
	cv_xp->waiters_sema  = CreateSemaphoreA (NULL, 0, MAXLONG, NULL);

	if (P_UNLIKELY (cv_xp->waiters_sema == NULL)) {
		P_ERROR ("PCondVariable::pp_cond_variable_init_xp: failed to initialize semaphore");
		p_free (cond->cv);
		cond->cv = NULL;
		return FALSE;
	}

	return TRUE;
}
Ejemplo n.º 22
0
static void test_RtlQueueWorkItem(void)
{
    HANDLE semaphore;
    NTSTATUS status;
    DWORD result;

    semaphore = CreateSemaphoreA(NULL, 0, 1, NULL);
    ok(semaphore != NULL, "CreateSemaphoreA failed %u\n", GetLastError());

    status = RtlQueueWorkItem(rtl_work_cb, semaphore, WT_EXECUTEDEFAULT);
    ok(!status, "RtlQueueWorkItem failed with status %x\n", status);
    result = WaitForSingleObject(semaphore, 1000);
    ok(result == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", result);

    status = RtlQueueWorkItem(rtl_work_cb, semaphore, WT_EXECUTEINIOTHREAD);
    ok(!status, "RtlQueueWorkItem failed with status %x\n", status);
    result = WaitForSingleObject(semaphore, 1000);
    ok(result == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", result);

    status = RtlQueueWorkItem(rtl_work_cb, semaphore, WT_EXECUTEINPERSISTENTTHREAD);
    ok(!status, "RtlQueueWorkItem failed with status %x\n", status);
    result = WaitForSingleObject(semaphore, 1000);
    ok(result == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", result);

    status = RtlQueueWorkItem(rtl_work_cb, semaphore, WT_EXECUTELONGFUNCTION);
    ok(!status, "RtlQueueWorkItem failed with status %x\n", status);
    result = WaitForSingleObject(semaphore, 1000);
    ok(result == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", result);

    status = RtlQueueWorkItem(rtl_work_cb, semaphore, WT_TRANSFER_IMPERSONATION);
    ok(!status, "RtlQueueWorkItem failed with status %x\n", status);
    result = WaitForSingleObject(semaphore, 1000);
    ok(result == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", result);

    CloseHandle(semaphore);
}
Ejemplo n.º 23
0
int __cdecl main (int argc, char **argv)
{
    int i;
    int j;

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return (FAIL);
    }
    /* create semaphores */
    for (i = 0; i < sizeof(testCases)/sizeof(struct testcase); i++)
    {
        hSemaphore[i] = CreateSemaphoreA (testCases[i].lpSemaphoreAttributes,
                                          testCases[i].lInitialCount,
                                          testCases[i].lMaximumCount,
                                          testCases[i].lpName);

        if (NULL == hSemaphore[i])
        {
            if (!testCases[i].bNegativeTest)
            {
                Trace("PALSUITE ERROR: CreateSemaphoreA('%p' '%ld' '%ld' "
                      "'%p') returned NULL at index %d.\nGetLastError "
                      "returned %d.\n", testCases[i].lpSemaphoreAttributes,
                      testCases[i].lInitialCount, testCases[i].lMaximumCount,
                      testCases[i].lpName, i, GetLastError());
                if (i > 0)
                {
                    cleanup(i - 1);
                }
                Fail("");
            }
            else
            {
                continue;
            }
        }
        /* incriment semaphore count to lMaximumCount */
        for (j = testCases[i].lInitialCount; j <= testCases[i].lMaximumCount;
                j++)
        {
            if (testCases[i].lMaximumCount == j)
            {
                /* Call ReleaseSemaphore once more to ensure ReleaseSemaphore
                   fails */
                if(ReleaseSemaphore(hSemaphore[i], 1, NULL))
                {
                    Trace("PALSUITE ERROR: ReleaseSemaphore('%p' '%ld' '%p') "
                          "call returned %d\nwhen it should have returned "
                          "%d.\nThe semaphore's count was %d.\nGetLastError "
                          "returned %d.\n", hSemaphore[i], 1, NULL, TRUE,
                          FALSE, j, GetLastError());
                    cleanup(i);
                    Fail("");
                }
            }
            else
            {
                int previous;
                BOOL bRet = ReleaseSemaphore(hSemaphore[i], 1, &previous);
                DWORD dwError = GetLastError();

                if(!bRet)
                {
                    Trace("PALSUITE ERROR: ReleaseSemaphore('%p' '%ld' '%p') "
                          "call returned %d\nwhen it should have returned "
                          "%d.\nThe semaphore count was %d and it's "
                          "lMaxCount was %d.\nGetLastError returned %d.\n",
                          hSemaphore[i], 1, &previous, bRet, TRUE, j,
                          testCases[i].lMaximumCount, dwError);
                    cleanup(i);
                    Fail("");
                }
                if (previous != j)
                {
                    Trace("PALSUITE ERROR: ReleaseSemaphore('%p' '%ld' '%p') "
                          "call set %p to %d instead of %d.\n The semaphore "
                          "count was %d and GetLastError returned %d.\n",
                          hSemaphore[i], 1, &previous, &previous, previous,
                          j, j, dwError);
                    cleanup(i);
                    Fail("");
                }
            }
        }
        /* decrement semaphore count to 0 */
        for (j = testCases[i].lMaximumCount; j >= 0; j--)
        {
            DWORD dwRet = WaitForSingleObject(hSemaphore[i], 0);
            DWORD dwError = GetLastError();

            if (0 == j)
            {
                /* WaitForSingleObject should report that the
                   semaphore is nonsignaled */
                if (WAIT_TIMEOUT != dwRet)
                {
                    Trace("PALSUITE ERROR: WaitForSingleObject('%p' '%u') "
                          "call returned %d\nwhen it should have returned "
                          "%d.\nThe semaphore's count was %d.\nGetLastError "
                          "returned %d.\n", hSemaphore[i], 0, dwRet,
                          WAIT_TIMEOUT, j, dwError);
                    cleanup(i);
                    Fail("");
                }
            }
            else
            {
                /* WaitForSingleObject should report that the
                   semaphore is signaled */
                if (WAIT_OBJECT_0 != dwRet)
                {
                    Trace("PALSUITE ERROR: WaitForSingleObject('%p' '%u') "
                          "call returned %d\nwhen it should have returned "
                          "%d.\nThe semaphore's count was %d.\nGetLastError "
                          "returned %d.\n", hSemaphore[i], 0, dwRet,
                          WAIT_OBJECT_0, j, dwError);
                    cleanup(i);
                    Fail("");
                }
            }
        }
    }
    PAL_Terminate();
    return (PASS);
}
Ejemplo n.º 24
0
    Setup the semaphore
 */
HANDLE QSystemLockPrivate::handle()
{
    // don't allow making handles on empty keys
    if (key.isEmpty())
        return 0;

    // Create it if it doesn't already exists.
    if (semaphore == 0) {
        QString safeName = makeKeyFileName();
        QT_WA({
            semaphore = CreateSemaphoreW(0, MAX_LOCKS, MAX_LOCKS, (TCHAR*)safeName.utf16());
        }, {
            semaphore = CreateSemaphoreA(0, MAX_LOCKS, MAX_LOCKS, safeName.toLocal8Bit().constData());
        });

        if (semaphore == 0) {
            setErrorString(QLatin1String("QSystemLockPrivate::handle"));
	    return 0;
	}
    }

    if (semaphoreLock == 0) {
	QString safeLockName = QSharedMemoryPrivate::makePlatformSafeKey(key + QLatin1String("lock"), QLatin1String("qipc_systemlock_"));
        QT_WA({
            semaphoreLock = CreateSemaphoreW(0,
                 1, 1, (TCHAR*)safeLockName.utf16());
        }, {
            semaphoreLock = CreateSemaphoreA(0,
Ejemplo n.º 25
0
static void test_tp_timer(void)
{
    TP_CALLBACK_ENVIRON environment;
    DWORD result, ticks;
    LARGE_INTEGER when;
    HANDLE semaphore;
    NTSTATUS status;
    TP_TIMER *timer;
    TP_POOL *pool;
    BOOL success;
    int i;

    semaphore = CreateSemaphoreA(NULL, 0, 1, NULL);
    ok(semaphore != NULL, "CreateSemaphoreA failed %u\n", GetLastError());

    /* allocate new threadpool */
    pool = NULL;
    status = pTpAllocPool(&pool, NULL);
    ok(!status, "TpAllocPool failed with status %x\n", status);
    ok(pool != NULL, "expected pool != NULL\n");

    /* allocate new timer */
    timer = NULL;
    memset(&environment, 0, sizeof(environment));
    environment.Version = 1;
    environment.Pool = pool;
    status = pTpAllocTimer(&timer, timer_cb, semaphore, &environment);
    ok(!status, "TpAllocTimer failed with status %x\n", status);
    ok(timer != NULL, "expected timer != NULL\n");

    success = pTpIsTimerSet(timer);
    ok(!success, "TpIsTimerSet returned TRUE\n");

    /* test timer with a relative timeout */
    when.QuadPart = (ULONGLONG)200 * -10000;
    pTpSetTimer(timer, &when, 0, 0);
    success = pTpIsTimerSet(timer);
    ok(success, "TpIsTimerSet returned FALSE\n");

    pTpWaitForTimer(timer, FALSE);

    result = WaitForSingleObject(semaphore, 100);
    ok(result == WAIT_TIMEOUT, "WaitForSingleObject returned %u\n", result);
    result = WaitForSingleObject(semaphore, 200);
    ok(result == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", result);
    success = pTpIsTimerSet(timer);
    ok(success, "TpIsTimerSet returned FALSE\n");

    /* test timer with an absolute timeout */
    NtQuerySystemTime( &when );
    when.QuadPart += (ULONGLONG)200 * 10000;
    pTpSetTimer(timer, &when, 0, 0);
    success = pTpIsTimerSet(timer);
    ok(success, "TpIsTimerSet returned FALSE\n");

    pTpWaitForTimer(timer, FALSE);

    result = WaitForSingleObject(semaphore, 100);
    ok(result == WAIT_TIMEOUT, "WaitForSingleObject returned %u\n", result);
    result = WaitForSingleObject(semaphore, 200);
    ok(result == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", result);
    success = pTpIsTimerSet(timer);
    ok(success, "TpIsTimerSet returned FALSE\n");

    /* test timer with zero timeout */
    when.QuadPart = 0;
    pTpSetTimer(timer, &when, 0, 0);
    success = pTpIsTimerSet(timer);
    ok(success, "TpIsTimerSet returned FALSE\n");

    pTpWaitForTimer(timer, FALSE);

    result = WaitForSingleObject(semaphore, 50);
    ok(result == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", result);
    success = pTpIsTimerSet(timer);
    ok(success, "TpIsTimerSet returned FALSE\n");

    /* unset the timer */
    pTpSetTimer(timer, NULL, 0, 0);
    success = pTpIsTimerSet(timer);
    ok(!success, "TpIsTimerSet returned TRUE\n");
    pTpWaitForTimer(timer, TRUE);

    pTpReleaseTimer(timer);
    CloseHandle(semaphore);

    semaphore = CreateSemaphoreA(NULL, 0, 3, NULL);
    ok(semaphore != NULL, "CreateSemaphoreA failed %u\n", GetLastError());

    /* allocate a new timer */
    timer = NULL;
    memset(&environment, 0, sizeof(environment));
    environment.Version = 1;
    environment.Pool = pool;
    status = pTpAllocTimer(&timer, timer_cb, semaphore, &environment);
    ok(!status, "TpAllocTimer failed with status %x\n", status);
    ok(timer != NULL, "expected timer != NULL\n");

    /* test a relative timeout repeated periodically */
    when.QuadPart = (ULONGLONG)200 * -10000;
    pTpSetTimer(timer, &when, 200, 0);
    success = pTpIsTimerSet(timer);
    ok(success, "TpIsTimerSet returned FALSE\n");

    /* wait until the timer was triggered three times */
    ticks = GetTickCount();
    for (i = 0; i < 3; i++)
    {
        result = WaitForSingleObject(semaphore, 1000);
        ok(result == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", result);
    }
    ticks = GetTickCount() - ticks;
    ok(ticks >= 500 && (ticks <= 700 || broken(ticks <= 750)) /* Win 7 */,
       "expected approximately 600 ticks, got %u\n", ticks);

    /* unset the timer */
    pTpSetTimer(timer, NULL, 0, 0);
    success = pTpIsTimerSet(timer);
    ok(!success, "TpIsTimerSet returned TRUE\n");
    pTpWaitForTimer(timer, TRUE);

    /* cleanup */
    pTpReleaseTimer(timer);
    pTpReleasePool(pool);
    CloseHandle(semaphore);
}
Ejemplo n.º 26
0
//---------------------------------------------------------
bool spoutMemoryShare::Initialize()
{
	#ifdef CONSOLE_DEBUG
	DWORD errnum;
	#endif

	// Have semaphore names been set ?
	if(!szShareMemoryName[0]) {
		setSharedMemoryName("spoutMemoryShare");
	}

	// Create or open read semaphore depending, on whether it already exists or not
	hReadSemaphore = CreateSemaphoreA ( 
						NULL,	// default security attributes
						1,		// initial count (do not allow a read until write allows it)
						1,		// maximum count
						(LPSTR)szReadSemaphoreName);

    if (hReadSemaphore == NULL) {
		#ifdef CONSOLE_DEBUG
        printf("Create Read Semaphore error\n");
		#endif
        return false;
    }
	#ifdef CONSOLE_DEBUG
	else {
		errnum = GetLastError();
		// printf("Read Semaphore GetLastError() = %d\n", errnum);
		if(errnum == ERROR_INVALID_HANDLE) {
			printf("Read Semaphore invalid handle\n");
		}
		if(errnum == ERROR_ALREADY_EXISTS) {
			printf("Read Semaphore [%s] already exists\n", szReadSemaphoreName);
		}
		else {
			printf("Read Semaphore [%s] created\n", szReadSemaphoreName);
		}
	}
	#endif

	hWriteSemaphore = CreateSemaphoreA ( 
						NULL,   // default security attributes
						1,		// initial count (allow write)
						1,		// maximum count
						(LPSTR)szWriteSemaphoreName);

    if (hWriteSemaphore == NULL) {
		#ifdef CONSOLE_DEBUG
        printf("Create Write Semaphore error\n");
		#endif
        return false;
    }
	#ifdef CONSOLE_DEBUG
	else {
		errnum = GetLastError();
		// printf("Write Semaphore GetLastError() = %d\n", errnum);
		if(errnum == ERROR_INVALID_HANDLE) {
			printf("Write Semaphore invalid handle\n");
		}
		if(errnum == ERROR_ALREADY_EXISTS) {
			printf("Write Semaphore [%s] already exists\n", szWriteSemaphoreName);
		}
		else {
			printf("Write Semaphore [%s] created\n", szWriteSemaphoreName);
		}
	}
	#endif

	// Each time a thread completes a wait for a semaphore object, 
	// the count of the semaphore object is decremented by one. 
	// When the thread has finished, it calls the ReleaseSemaphore function, 
	// which increments the count of the semaphore object.
     
    // Set up Shared Memory
	// allocate space for an rgb bitmap the size of the desktop, then nothing will be bigger
	DWORD size = (DWORD)( sizeof(BITMAPINFOHEADER)+GetSystemMetrics(SM_CXSCREEN)*GetSystemMetrics(SM_CYSCREEN)*3 );

    // Create or open shared memory, depending on whether it already exists or not
	// Must be CreateFileMappingA, not CreateFileMapping or it doesn't work
    hSharedMemory = CreateFileMappingA ( INVALID_HANDLE_VALUE,			// use paging file
										 NULL,							// default security 
										 PAGE_READWRITE,				// read/write access
										 0,								// max. object size 
										 size,							// buffer size  
										 (LPCSTR)szShareMemoryName);	// name of mapping object
	
    if (hSharedMemory == NULL || hSharedMemory == INVALID_HANDLE_VALUE) { 
		#ifdef CONSOLE_DEBUG
		printf("Error occured while creating file mapping object : %d\n", GetLastError() );
		#endif
        return false;
    }
	#ifdef CONSOLE_DEBUG
	else {
		errnum = GetLastError();
		// printf("map name = %s : GetLastError() = %d\n", szShareMemoryName, errnum);
		if(errnum == ERROR_INVALID_HANDLE) {
			printf("map invalid handle\n");
		}
		if(errnum == ERROR_ALREADY_EXISTS) {
			printf("map already exists\n");
			// here we can set bIsClient also
		}
		else {
			printf("map created OK\n");
		}
	}
	#endif

    pBuffer = (LPTSTR)MapViewOfFile(	hSharedMemory,			// handle to map object
										FILE_MAP_ALL_ACCESS,	// read/write permission
										0,                   
										0,                   
										size);

    if (NULL == pBuffer) { 
		#ifdef CONSOLE_DEBUG
		printf("Error occured while mapping view of the file : %d\n", GetLastError() );
		#endif
        return false;
    }

	// ==== SEMAPHORES ====

     
    return true;

} // end Initialize
Ejemplo n.º 27
0
static void test_tp_window_length(void)
{
    struct window_length_info info1, info2;
    TP_CALLBACK_ENVIRON environment;
    TP_TIMER *timer1, *timer2;
    LARGE_INTEGER when;
    HANDLE semaphore;
    NTSTATUS status;
    TP_POOL *pool;
    DWORD result;

    semaphore = CreateSemaphoreA(NULL, 0, 2, NULL);
    ok(semaphore != NULL, "CreateSemaphoreA failed %u\n", GetLastError());

    /* allocate new threadpool */
    pool = NULL;
    status = pTpAllocPool(&pool, NULL);
    ok(!status, "TpAllocPool failed with status %x\n", status);
    ok(pool != NULL, "expected pool != NULL\n");

    /* allocate two identical timers */
    memset(&environment, 0, sizeof(environment));
    environment.Version = 1;
    environment.Pool = pool;

    timer1 = NULL;
    info1.semaphore = semaphore;
    status = pTpAllocTimer(&timer1, window_length_cb, &info1, &environment);
    ok(!status, "TpAllocTimer failed with status %x\n", status);
    ok(timer1 != NULL, "expected timer1 != NULL\n");

    timer2 = NULL;
    info2.semaphore = semaphore;
    status = pTpAllocTimer(&timer2, window_length_cb, &info2, &environment);
    ok(!status, "TpAllocTimer failed with status %x\n", status);
    ok(timer2 != NULL, "expected timer2 != NULL\n");

    /* choose parameters so that timers are not merged */
    info1.ticks = 0;
    info2.ticks = 0;

    NtQuerySystemTime( &when );
    when.QuadPart += (ULONGLONG)250 * 10000;
    pTpSetTimer(timer2, &when, 0, 0);
    Sleep(50);
    when.QuadPart -= (ULONGLONG)150 * 10000;
    pTpSetTimer(timer1, &when, 0, 75);

    result = WaitForSingleObject(semaphore, 1000);
    ok(result == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", result);
    result = WaitForSingleObject(semaphore, 1000);
    ok(result == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", result);
    ok(info1.ticks != 0 && info2.ticks != 0, "expected that ticks are nonzero\n");
    ok(info2.ticks >= info1.ticks + 75 || broken(info2.ticks < info1.ticks + 75) /* Win 2008 */,
       "expected that timers are not merged\n");

    /* timers will be merged */
    info1.ticks = 0;
    info2.ticks = 0;

    NtQuerySystemTime( &when );
    when.QuadPart += (ULONGLONG)250 * 10000;
    pTpSetTimer(timer2, &when, 0, 0);
    Sleep(50);
    when.QuadPart -= (ULONGLONG)150 * 10000;
    pTpSetTimer(timer1, &when, 0, 200);

    result = WaitForSingleObject(semaphore, 1000);
    ok(result == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", result);
    result = WaitForSingleObject(semaphore, 1000);
    ok(result == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", result);
    ok(info1.ticks != 0 && info2.ticks != 0, "expected that ticks are nonzero\n");
    ok(info2.ticks >= info1.ticks - 50 && info2.ticks <= info1.ticks + 50,
       "expected that timers are merged\n");

    /* on Windows the timers also get merged in this case */
    info1.ticks = 0;
    info2.ticks = 0;

    NtQuerySystemTime( &when );
    when.QuadPart += (ULONGLONG)100 * 10000;
    pTpSetTimer(timer1, &when, 0, 200);
    Sleep(50);
    when.QuadPart += (ULONGLONG)150 * 10000;
    pTpSetTimer(timer2, &when, 0, 0);

    result = WaitForSingleObject(semaphore, 1000);
    ok(result == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", result);
    result = WaitForSingleObject(semaphore, 1000);
    ok(result == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", result);
    ok(info1.ticks != 0 && info2.ticks != 0, "expected that ticks are nonzero\n");
    todo_wine
    ok(info2.ticks >= info1.ticks - 50 && info2.ticks <= info1.ticks + 50,
       "expected that timers are merged\n");

    /* cleanup */
    pTpReleaseTimer(timer1);
    pTpReleaseTimer(timer2);
    pTpReleasePool(pool);
    CloseHandle(semaphore);
}
Ejemplo n.º 28
0
	bool CShareMem::Create(std::string strSMName, unsigned unSMMSize)
	{
		bool bResult = false;
		do 
		{
			if(strSMName.empty() || 0 == unSMMSize || unSMMSize < sizeof(SWRPos))
				break;

			m_strSMName = strSMName;


			SECURITY_ATTRIBUTES SecAttr, *pSec = 0;
			SECURITY_DESCRIPTOR SecDesc;  
			if (strSMName.find("Global\\") != std::string::npos) 
			{     
				InitializeSecurityDescriptor(&SecDesc, SECURITY_DESCRIPTOR_REVISION);
				SetSecurityDescriptorDacl(&SecDesc, TRUE, (PACL)0, FALSE);  //Add the ACL to the security descriptor.这里设置的是一个空的DACL
				SecAttr.nLength = sizeof(SecAttr); 
				SecAttr.lpSecurityDescriptor = &SecDesc;  
				SecAttr.bInheritHandle = TRUE;  
				pSec = &SecAttr; 
			}


			std::string strMutexName = strSMName + "Mutex";
			m_hMutexSyncData = CreateMutexA(pSec, FALSE, strMutexName.c_str());
			if(NULL == m_hMutexSyncData)
				break;

			std::string strSemName = strSMName + "Recv";
			m_hWait[0] = CreateSemaphoreA(pSec, 0, 5000, strSemName.c_str());
			if(NULL == m_hWait[0])
				break;

			std::string strSemExit = strSMName + "Exit";
			m_hWait[1] = CreateSemaphoreA(pSec, 0, 1, strSemExit.c_str());
			if(NULL == m_hWait[0])
				break;


			//当你创建了一个命名管道,它的安全参数指定了NULL,这就表明只有创建者才可以作为Client访问这个命名管道。
			m_hFileMapObj = CreateFileMappingA(INVALID_HANDLE_VALUE, pSec, PAGE_READWRITE, 0, unSMMSize, strSMName.c_str());
			DWORD gg = GetLastError();
			if(NULL == m_hFileMapObj)
				break;

			//将其映射到本进程的地址空间中
			m_pMapView	= (char *)MapViewOfFile(m_hFileMapObj, FILE_MAP_ALL_ACCESS, 0, 0, 0); 
			if(NULL == m_pMapView)
				break;

			m_pWRPos = reinterpret_cast<PSWRPos>(m_pMapView);
			m_pWRPos->mem_len   = unSMMSize - sizeof(SWRPos);
			m_pWRPos->read_pos  = 0;
			m_pWRPos->write_pos = 0;
			m_pUserBufBasePos = m_pMapView + sizeof(SWRPos);

			m_bSMSuccess = bResult = true;
		} while (false);

		if(!bResult)
		{
			close();
		}

		return bResult;
	}
Ejemplo n.º 29
0
    }
}

HANDLE QSystemSemaphorePrivate::handle(QSystemSemaphore::AccessMode)
{
    // don't allow making handles on empty keys
    if (key.isEmpty())
        return 0;

    // Create it if it doesn't already exists.
    if (semaphore == 0) {
        QString safeName = makeKeyFileName();
        QT_WA({
            semaphore = CreateSemaphoreW(0, initialValue, MAXLONG, (TCHAR*)safeName.utf16());
        }, {
            semaphore = CreateSemaphoreA(0, initialValue, MAXLONG, safeName.toLocal8Bit().constData());
        });
        if (semaphore == NULL)
            setErrorString(QLatin1String("QSystemSemaphore::handle"));
    }

    return semaphore;
}

void QSystemSemaphorePrivate::cleanHandle()
{
    if (semaphore && !CloseHandle(semaphore)) {
#if defined QSYSTEMSEMAPHORE_DEBUG
        qDebug() << QLatin1String("QSystemSemaphorePrivate::CloseHandle: sem failed");
#endif
    }
Ejemplo n.º 30
0
int main(int argc, char* argv[])
{


	LPTHREAD_START_ROUTINE routine[CORE_NUMBER];
	
	int i,j;
	int stacksize = 8000;

	_argc = argc;
	_argv = argv;


	routine[0] = computationThread_Core1;
	/*routine[1] = computationThread_Core1;
	routine[2] = computationThread_Core2;
	routine[3] = computationThread_Core3;
	routine[4] = computationThread_Core4;
	routine[5] = computationThread_Core5;
	routine[6] = computationThread_Core6;
	routine[7] = computationThread_Core7;*/

	for(i=0;i<MEDIA_NR;i++){
		for(j=0;j<MEDIA_NR;j++){
			char sem_name[20]="sem_init";
			char sem_num[4];

			if(i!=j){
				_itoa_s(i,sem_num,2,10);
				strcat_s(sem_name,20,sem_num);
				strcat_s(sem_name,20,"_");
				_itoa_s(j,sem_num,2,10);
				strcat_s(sem_name,20,sem_num);
				sem_init[i][j] = CreateSemaphoreA(NULL,1,1,sem_name);
			}
		}
	}



	for(i=0;i<CORE_NUMBER;i++){
		HANDLE thread = CreateThread(NULL,stacksize,routine[i],NULL,0,NULL);
		SetThreadAffinityMask(thread,1<<i);
		/*SetThreadPriority(
		thread,
		THREAD_PRIORITY_HIGHEST
		);*/

	}

	/*
	{
		HANDLE semaphore = CreateSemaphore (NULL,0,1,"semaphore");
		WaitForSingleObject(semaphore,INFINITE);
	}*/

	for(i=0;i<1000000000;i++){
		i--;
	}

	return 0;
}