void __fastcall receive_interrupt (CONTEXT *context, int type, void *arg)
#endif
{
  signal_queue_t* sq;
  interrupt_queue_t* interrupt_info;

  readytoreturn = FALSE;

  if (DEBUG)
    kprintf("SYS:Running user interrupt handler, context = 0x%x, arg = 0x%x.\n",
	   context, arg);
  
  /* find the appropriate handler */
  interrupt_info = interrupt_queue;
  while (interrupt_info!=NULL && interrupt_info->type!=type)
    interrupt_info = interrupt_info->next;

  if (interrupt_info == NULL) {
    /* we couldn't find the interrupt with type "type" so we crask the
       sistem.
    */
    kprintf("An interrupt of the unregistered type %d was received. Crashing.\n ",
	   type);
    exit(-1);
  } else {
    /* now, call the appropriate interrupt handler */
    if (DEBUG)
      kprintf("SYS:interrupt of type %d.\n", type);
    if (interrupt_info->handler != NULL)
      interrupt_info->handler(arg); 
  }
  
  WaitOnObject(mutex);
  assert(signalq == NULL);

  sq = (signal_queue_t *) malloc(sizeof(signal_queue_t));
  sq->context = context;
  sq->threadid = system_thread;

  sq->next = signalq;
  signalq = sq;

  if (interrupt_level == ENABLED) {
    if (DEBUG)
      kprintf("SYS:disabling interrupts in handler.\n");
    interrupt_level = DISABLED;
  }  
  ReleaseMutex(mutex);

  /* 
   * This is correct but not elegant (it's a kluge forced on us by Windows).
   * We need an atomic way to wake up the
   * assist thread and go to sleep ourselves. One could use SignalAndWait
   * here, but SignalAndWait is not supported on CE 
   */
  ReleaseSemaphore(cleanup, 1, NULL); /* tell the return thread to run */

  readytoreturn = TRUE;

  /* if (DEBUG) kprintf("SYS:Looping forever.\n"); */
  loopforever();
}
示例#2
0
void
omni_semaphore::post(void)
{
    if (!ReleaseSemaphore(nt_sem, 1, NULL))
	throw omni_thread_fatal(GetLastError());
}
示例#3
0
void CKDMTCriticalSection::Stop()
{
	if (!ReleaseSemaphore(m_hSemaphore, 1, NULL))
		TRACE(_T("CKDMTCriticalSection::Stop release semaphore failed\n"));
}
示例#4
0
static WRes Semaphore_Release(CSemaphore *p, LONG releaseCount, LONG *previousCount)
{ return BOOLToWRes(ReleaseSemaphore(*p, releaseCount, previousCount)); }
int mzrt_sema_post(mzrt_sema *s)
{
  ReleaseSemaphore(s->ws, 1, NULL);  
  return 0;
}
示例#6
0
void Semaphore::post()
{
  VERIFY(ReleaseSemaphore((HANDLE)handle, 1, 0));
}
示例#7
0
int get_site_entry(struct opusftp_globals *og,struct site_entry *e,IPCData *ipc)
{
struct List *list;
struct Node *node,*next;
int type=MATCH_NONE;
int result=0;
struct site_entry *site;

if	(!e)
	return(FALSE);


ObtainSemaphoreShared(&og->og_SiteList_semaphore);

if	(!og->og_SiteList)
	read_build_addressbook(og,ipc);

if	(!og->og_SiteList)
	goto  done;

if	(*e->se_name)	type=MATCH_NAME;

else if (*e->se_host)	type=MATCH_HOST;
else			goto done;

list=&og->og_SiteList->list;

if	(list && !IsListEmpty(list))
	{
	if	((node=list->lh_Head))
		{
		int count=0;
		while	((next=node->ln_Succ))
			{
			int found;

			count++;

			site=(struct site_entry *)((Att_Node *)node)->data;

			if	(type==MATCH_NAME)
				found=stricmp(e->se_name,site->se_name);
			else
				found=stricmp(e->se_host,site->se_host);

			if	(found==0)
				{
				// copy site entry
				copy_site_entry(og,e,site);

				// keep match position as return value
				result=count;
				break;
				}

			node=next;
	 		}
		}
	}


done:

ReleaseSemaphore(&og->og_SiteList_semaphore);

return(result);
}
示例#8
0
// Internal API functions
static int wince_init(struct libusb_context *ctx)
{
	int r = LIBUSB_ERROR_OTHER;
	HANDLE semaphore;
	LARGE_INTEGER li_frequency;
	TCHAR sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)

	_stprintf(sem_name, _T("libusb_init%08X"), (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
	semaphore = CreateSemaphore(NULL, 1, 1, sem_name);
	if (semaphore == NULL) {
		usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
		return LIBUSB_ERROR_NO_MEM;
	}

	// A successful wait brings our semaphore count to 0 (unsignaled)
	// => any concurent wait stalls until the semaphore's release
	if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
		usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
		CloseHandle(semaphore);
		return LIBUSB_ERROR_NO_MEM;
	}

	// NB: concurrent usage supposes that init calls are equally balanced with
	// exit calls. If init is called more than exit, we will not exit properly
	if ( ++concurrent_usage == 0 ) {	// First init?
		// Initialize pollable file descriptors
		init_polling();

		// Load DLL imports
		if (init_dllimports() != LIBUSB_SUCCESS) {
			usbi_err(ctx, "could not resolve DLL functions");
			r = LIBUSB_ERROR_NOT_SUPPORTED;
			goto init_exit;
		}

		// try to open a handle to the driver
		driver_handle = UkwOpenDriver();
		if (driver_handle == INVALID_HANDLE_VALUE) {
			usbi_err(ctx, "could not connect to driver");
			r = LIBUSB_ERROR_NOT_SUPPORTED;
			goto init_exit;
		}

		// find out if we have access to a monotonic (hires) timer
		if (QueryPerformanceFrequency(&li_frequency)) {
			hires_frequency = li_frequency.QuadPart;
			// The hires frequency can go as high as 4 GHz, so we'll use a conversion
			// to picoseconds to compute the tv_nsecs part in clock_gettime
			hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency;
			usbi_dbg("hires timer available (Frequency: %"PRIu64" Hz)", hires_frequency);
		} else {
			usbi_dbg("no hires timer available on this platform");
			hires_frequency = 0;
			hires_ticks_to_ps = UINT64_C(0);
		}
	}
	// At this stage, either we went through full init successfully, or didn't need to
	r = LIBUSB_SUCCESS;

init_exit: // Holds semaphore here.
	if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
		if (driver_handle != INVALID_HANDLE_VALUE) {
			UkwCloseDriver(driver_handle);
			driver_handle = INVALID_HANDLE_VALUE;
		}
	}

	if (r != LIBUSB_SUCCESS)
		--concurrent_usage; // Not expected to call libusb_exit if we failed.

	ReleaseSemaphore(semaphore, 1, NULL);	// increase count back to 1
	CloseHandle(semaphore);
	return r;
}
示例#9
0
shared_memory::status shared_memory::lock(lock_descriptor& lck, unsigned msec)
{
    //assert(lck.mode == lck_shared || lck.mode == lck_exclusive);

	if(!(lck.mode == lck_shared || lck.mode == lck_exclusive))
			global_func_log(__LINE__,__FILE__, NULL);

    unsigned self = GetCurrentThreadId();
    status result;

    if (self == owner) 
	{ 
	//assert(n_nested_exclusive_locks != 0 && pMonitor->n_writers == 1);

	if(!(n_nested_exclusive_locks != 0 && pMonitor->n_writers == 1))
			global_func_log(__LINE__,__FILE__, NULL);

	if (lck.mode == lck_exclusive) { 
	    n_nested_exclusive_locks += 1;
	} else {
	    pMonitor->n_readers += 1;
	    lck.owner = self;
	    lck.next = shared_lock_chain;
	    shared_lock_chain = &lck;
	}
	return ok;
    }
    if (!enter_critical_section(result)) { 
	return result;
    }
    if (lck.mode == lck_shared) { 
	while (pMonitor->n_writers != 0) { 
	    // storage is exclusivly locked by another process
	    if (msec != 0) { 
		if (pMonitor->n_waiters++ == 0) { 
		    ResetEvent(hEvent);
		}
	    }
	    if (!leave_critical_section(result)) { 
		return result;
	    }
	    if (msec == 0) { 
		return timeout_expired;
	    }
	    int rc = WaitForSingleObject(hEvent, msec);  
	    if (rc == WAIT_TIMEOUT) { 
		msec = 0;
	    } else if (rc != WAIT_OBJECT_0) {
		return status(GetLastError());
	    }		 
	    ReleaseSemaphore(hSemaphore, 1, NULL);
	    if (!enter_critical_section(result)) { 
		return result;
	    }
	} 
	pMonitor->n_readers += 1;
	lck.owner = self;
	lck.next = shared_lock_chain;
	shared_lock_chain = &lck;
    } else { // exclusive lock
	while (pMonitor->n_writers != 0 
	       || (pMonitor->n_readers != 0 
		   && (pMonitor->n_readers != 1 
		       || shared_lock_chain == NULL
		       || shared_lock_chain->owner != self))) 
        { 
	    // storage is locked by another process
	    if (msec != 0) { 
		if (pMonitor->n_waiters++ == 0) { 
		    ResetEvent(hEvent);
		}
	    }
	    if (!leave_critical_section(result)) { 
		return result;
	    }
	    if (msec == 0) { 
		return timeout_expired;
	    }
	    int rc = WaitForSingleObject(hEvent, msec);  
	    if (rc == WAIT_TIMEOUT) { 
		msec = 0;
	    } else if (rc != WAIT_OBJECT_0) {
		return status(GetLastError());
	    }		 
	    ReleaseSemaphore(hSemaphore, 1, NULL);
	    if (!enter_critical_section(result)) { 
		return result;
	    }
	} 
	pMonitor->n_writers = 1;
	n_nested_exclusive_locks = 1;
	owner = self;
    }
    return leave_critical_section(result) ? ok : result;
}
示例#10
0
文件: semctl.c 项目: nawhizz/KAIT
int CBD1
semctl(int semid, int semnum, int cmd, ...)
{
	BOOL	ret;
	int	iret;
	DWORD	dwret;
	int	i, j, diffsemval;
#ifndef TERMINAL_SERVICE
	char	semstr[16];
#else
	char	semstr[30];
#endif	/* TERMINAL_SERVICE */
	BOOL	lret;
	HANDLE	hsem;
	int	piid;
	DWORD	procid;
	va_list vlist;
	union	semun	semarg;
	LPTSTR	lpszPipeName = "\\\\.\\pipe\\ipcd";
	SCBUF	scIn, scOut;
	DWORD	bytesRead;
	HANDLE	hIpct = NULL;
	IPCT	*ipct = NULL;
#ifdef	TERMINAL_SERVICE
	OSVERSIONINFOEX osvi;

	ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);

	if( !GetVersionEx ((OSVERSIONINFO *) &osvi) )
	{
	  // If OSVERSIONINFOEX doesn't work, try OSVERSIONINFO.
		osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
		GetVersionEx( (OSVERSIONINFO *) &osvi );
	}
#endif	/* TERMINAL_SERVICE */

//	StartIPCD();
	if (semid<0 || semid>=MAXNOOFIPC)
	{
		errno=EINVAL;
		return -1;
	}

	if (GetIPCT(&hIpct, &ipct)<0)
	{
		errno=EFAULT;
		return -1;
	}

	if (ipct->semt[semid].key<0)
	{
		procid=GetCurrentProcessId();
		piid=FindPINFO(OPT_SEM, procid, ipct);
		if (piid>=0)
		{
			for (i=0; i<MAXNSEM; i++)
				ipct->pseminfo[piid].semadj[semid][i]=0;
			ipct->pseminfo[piid].semid[semid]=0;
			InitPINFO(OPT_SEM, piid, ipct);
		}
		errno=EINVAL;
		FreeIPCT(hIpct, ipct);
		return -1;
	}

	if (semnum<0 || semnum>ipct->semt[semid].semds.sem_nsems)
	{
		errno=EINVAL;
		FreeIPCT(hIpct, ipct);
		return -1;
	}

	va_start(vlist, cmd);
	semarg=va_arg(vlist, union semun);
	va_end(vlist);

	switch (cmd)
	{
	case	IPC_STAT:
		if (semarg.buf == NULL)
		{
			FreeIPCT(hIpct, ipct);
			return -1;
		}

		memcpy((PSTR)semarg.buf, (PSTR)&ipct->semt[semid].semds,
						sizeof(ipct->semt[semid].semds));
		FreeIPCT(hIpct, ipct);
		return 0;

	case	IPC_RMID:

		scIn.cmd=SNO_SEMCTL;
		scIn.data=semid;

		lret = CallNamedPipe(lpszPipeName,
			 (char *)&scIn, sizeof(scIn),
			 (char *)&scOut, sizeof(scOut),
			 &bytesRead, NMPWAIT_WAIT_FOREVER);

		if (lret==FALSE)
		{
			errno=GetLastError();
			FreeIPCT(hIpct, ipct);
			return -1;
		}
		if (scOut.cmd!=SNO_OK)
		{
			errno=scOut.data;
			FreeIPCT(hIpct, ipct);
			return -1;
		}

		if( InitSEMT(semid, ipct) < 0 )
			return -1;

		for (i=0; i<MAXNOOFIPC; i++)
		{
			for (j=0; j<MAXNSEM; j++)
				ipct->pseminfo[i].semadj[semid][j]=0;
			ipct->pseminfo[i].semid[semid]=0;
			InitPINFO(OPT_SEM, i, ipct);
		}


		FreeIPCT(hIpct, ipct);
		return 0;

	case	GETVAL:
		iret=ipct->semb[semid][semnum].semval;
		FreeIPCT(hIpct, ipct);
		return iret;

	case	SETVAL:
		if (semarg.val < 0)
		{
			errno = EINVAL;
			FreeIPCT(hIpct, ipct);
			return -1;
		}

		diffsemval=semarg.val-ipct->semb[semid][semnum].semval;

#ifndef TERMINAL_SERVICE
		MakeSemstr(semstr, semnum, semid, ipct->semt[semid].key);
#else
		if( osvi.dwMajorVersion >= 5 )	/* Windows 2000 */
			MakeGlobalSemstr(semstr, semnum, semid, ipct->semt[semid].key);
		else
			MakeSemstr(semstr, semnum, semid, ipct->semt[semid].key);
#endif	/* TERMINAL_SERVICE */
		hsem=OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, semstr);
		if (hsem==NULL)
		{
			errno=GetLastError();
			FreeIPCT(hIpct, ipct);
			return -1;
		}
		for (i=0; i<abs(diffsemval); i++)
		{
			if (diffsemval>0)
			{
				ret=ReleaseSemaphore(hsem, diffsemval, NULL);
				if (ret==FALSE)
				{
					errno=GetLastError();
					CloseHandle(hsem);
					FreeIPCT(hIpct, ipct);
					return -1;
				}
				break;	/*2000.4.19*/
			}
			else if (diffsemval<0)
			{
/********************
				do
				{
					dwret=MsgWaitForMultipleObjects(1, &hsem,
						FALSE, INFINITE,
						QS_SENDMESSAGE|QS_POSTMESSAGE|QS_TIMER);
********************/
				dwret=WaitForSingleObject(hsem, INFINITE);

				switch (dwret)
				{
/********************
				case	WAIT_OBJECT_0 + 1 :
					if (l_peekmessage()<0)
					{
						CloseHandle(hsem);
						FreeIPCT(hIpct, ipct);
						return -1;
					}
					break;
********************/

				case	WAIT_OBJECT_0	:
					break;

				case	WAIT_TIMEOUT	:
				case	WAIT_FAILED	:
					errno=GetLastError();
				default :
					CloseHandle(hsem);
					FreeIPCT(hIpct, ipct);
					return -1;
				}
/*************
				} while (dwret==(WAIT_OBJECT_0 + 1));
*************/
			}
		}
		CloseHandle(hsem);

		ipct->semb[semid][semnum].semval=semarg.val;
		for (i=0; i<MAXNOOFIPC; i++)
			ipct->pseminfo[i].semadj[semid][semnum]=0;

		FreeIPCT(hIpct, ipct);
		return 0;

	case	GETPID:
		iret=ipct->semb[semid][semnum].sempid;
		FreeIPCT(hIpct, ipct);
		return iret;

	case	GETNCNT:
		iret=ipct->semb[semid][semnum].semncnt;
		FreeIPCT(hIpct, ipct);
		return iret;

	case	GETZCNT:
		iret=ipct->semb[semid][semnum].semzcnt;
		FreeIPCT(hIpct, ipct);
		return iret;

	case	GETALL:
		if (semarg.array == NULL)
		{
			errno=EINVAL;
			FreeIPCT(hIpct, ipct);
			return -1;
		}

		for (i=0; i<ipct->semt[semid].semds.sem_nsems; i++)
			semarg.array[i]=(short)ipct->semb[semid][i].semval;

		FreeIPCT(hIpct, ipct);
		return 0;

	case	SETALL:
		/* #####PENDING */
		FreeIPCT(hIpct, ipct);
		return 0;

	default:
		FreeIPCT(hIpct, ipct);
		return -1;
	}

}
示例#11
0
文件: thread.c 项目: fzls/myhtml
myhtml_status_t myhtml_hread_mutex_post(mythread_t *mythread, mythread_context_t *ctx)
{
    ReleaseSemaphore(ctx->mutex, 1, NULL);
    
    return MyHTML_STATUS_OK;
}
示例#12
0
//						===============
void					Semaphore::Post()
//						===============
{ 
	// Post message notifying a wait call
	ReleaseSemaphore(m_semaphore, 1, (long*)0);
}
示例#13
0
static int GM_UNIQUENAME(Open)(LIBBASETYPEPTR hdskBase, struct IOExtTD *iotd, IPTR unitnum, ULONG flags)
{
    STRPTR unitname;
    struct unit *unit;
    UBYTE unitflags = 0;

    if (unitnum < 1024)
    {
        ULONG len = strlen(hdskBase->DiskDevice) + 5;

        unitname = AllocVec(len, MEMF_ANY);
        if (!unitname)
            return FALSE;

        unitflags = UNIT_FREENAME;
        NewRawDoFmt(hdskBase->DiskDevice, (VOID_FUNC)RAWFMTFUNC_STRING, unitname, unitnum + hdskBase->unitBase);
    }
    else
        unitname = (STRPTR)unitnum;

    D(bug("hostdisk: open unit %s\n", unitname));

    ObtainSemaphore(&hdskBase->sigsem);

    unit = (struct unit *)FindName(&hdskBase->units, unitname);

    if (unit)
    {
        unit->usecount++;
        ReleaseSemaphore(&hdskBase->sigsem);
            
        iotd->iotd_Req.io_Unit                    = (struct Unit *)unit;
        iotd->iotd_Req.io_Error                   = 0;
        iotd->iotd_Req.io_Message.mn_Node.ln_Type = NT_REPLYMSG;

        DOPEN(bug("hostdisk: in libopen func. Yep. Unit is already open\n"));    
        return TRUE;
    }

    DOPEN(bug("hostdisk: in libopen func. No, it is not. So creating new unit ...\n"));

    unit = (struct unit *)AllocMem(sizeof(struct unit), MEMF_PUBLIC | MEMF_CLEAR);

    if (unit != NULL)
    {
        ULONG p = strlen(GM_UNIQUENAME(LibName));
        char taskName[p + strlen(unitname) + 2];
        struct Task *unitTask;

        DOPEN(bug("hostdisk: in libopen func. Allocation of unit memory okay. Setting up unit and calling CreateNewProc ...\n"));

        CopyMem(GM_UNIQUENAME(LibName), taskName, p);
        taskName[p] = ' ';
        strcpy(&taskName[p + 1], unitname);

        unit->n.ln_Name = unitname;
        unit->usecount  = 1;
        unit->hdskBase  = hdskBase;
        unit->flags     = unitflags;
        NEWLIST((struct List *)&unit->changeints);

        iotd->iotd_Req.io_Unit = (struct Unit *)unit;
        SetSignal(0, SIGF_SINGLE);
        unitTask = NewCreateTask(TASKTAG_PC  , unitentry,
                                 TASKTAG_NAME, taskName,
                                 TASKTAG_ARG1, iotd,
                                 TAG_DONE);

        DOPEN(bug("hostdisk: in libopen func. NewCreateTask() called. Task = 0x%p\n", unitTask));

        if (unitTask)
        {
            DOPEN(bug("hostdisk: in libopen func. Waiting for signal from unit task...\n"));
            Wait(SIGF_SINGLE);

            DOPEN(bug("hostdisk: in libopen func. Unit error %u, flags 0x%02X\n", iotd->iotd_Req.io_Error, unit->flags));
            if (!iotd->iotd_Req.io_Error)
            {
                AddTail((struct List *)&hdskBase->units, &unit->n);
                ReleaseSemaphore(&hdskBase->sigsem);
                return TRUE;
            }
        }
        else
            iotd->iotd_Req.io_Error = TDERR_NoMem;

        freeUnit(unit);
    }
    else
        iotd->iotd_Req.io_Error = TDERR_NoMem;

    ReleaseSemaphore(&hdskBase->sigsem);

    return FALSE;
}
示例#14
0
文件: semaphore.cpp 项目: respu/yield
void Semaphore::post() {
  ReleaseSemaphore(hSemaphore, 1, NULL);
}
示例#15
0
DWORD WINAPI wf_peer_main_loop(LPVOID lpParam)
{
	wfInfo* wfi;
	DWORD nCount;
	DWORD status;
	HANDLE handles[32];
	rdpSettings* settings;
	wfPeerContext* context;
	freerdp_peer* client = (freerdp_peer*) lpParam;

	if (!getenv("HOME"))
	{
		char home[MAX_PATH * 2] = "HOME=";
		strcat(home, getenv("HOMEDRIVE"));
		strcat(home, getenv("HOMEPATH"));
		_putenv(home);
	}

	wf_peer_init(client);

	settings = client->settings;
	settings->RemoteFxCodec = TRUE;
	settings->ColorDepth = 32;
	settings->NSCodec = FALSE;
	settings->JpegCodec = FALSE;
	wf_peer_read_settings(client);

	client->PostConnect = wf_peer_post_connect;
	client->Activate = wf_peer_activate;
	client->Logon = wf_peer_logon;

	client->input->SynchronizeEvent = wf_peer_synchronize_event;
	client->input->KeyboardEvent = wf_peer_keyboard_event;
	client->input->UnicodeKeyboardEvent = wf_peer_unicode_keyboard_event;
	client->input->MouseEvent = wf_peer_mouse_event;
	client->input->ExtendedMouseEvent = wf_peer_extended_mouse_event;

	client->Initialize(client);
	context = (wfPeerContext*) client->context;

	if (context->socketClose)
		return 0;

	wfi = context->info;

	if (wfi->input_disabled)
	{
		DEBUG_WARN("client input is disabled\n");
		client->input->KeyboardEvent = wf_peer_keyboard_event_dummy;
		client->input->UnicodeKeyboardEvent = wf_peer_unicode_keyboard_event_dummy;
		client->input->MouseEvent = wf_peer_mouse_event_dummy;
		client->input->ExtendedMouseEvent = wf_peer_extended_mouse_event_dummy;
	}

	context->socketEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	
	context->socketSemaphore = CreateSemaphore(NULL, 0, 1, NULL);
	context->socketThread = CreateThread(NULL, 0, wf_peer_socket_listener, client, 0, NULL);

	DEBUG_WARN("We've got a client %s\n", client->local ? "(local)" : client->hostname);

	nCount = 0;
	handles[nCount++] = context->updateEvent;
	handles[nCount++] = context->socketEvent;

	while (1)
	{
		status = WaitForMultipleObjects(nCount, handles, FALSE, INFINITE);

		if ((status == WAIT_FAILED) || (status == WAIT_TIMEOUT))
		{
			DEBUG_WARN("WaitForMultipleObjects failed\n");
			break;
		}

		if (WaitForSingleObject(context->updateEvent, 0) == 0)
		{
			if (client->activated)
				wf_update_peer_send(wfi, context);

			ResetEvent(context->updateEvent);
			ReleaseSemaphore(wfi->updateSemaphore, 1, NULL);
		}

		if (WaitForSingleObject(context->socketEvent, 0) == 0)
		{
			if (client->CheckFileDescriptor(client) != TRUE)
			{
				//printf("Failed to check peer file descriptor\n");
				context->socketClose = TRUE;
			}

			ResetEvent(context->socketEvent);
			ReleaseSemaphore(context->socketSemaphore, 1, NULL);

			if (context->socketClose)
				break;
		}

		//force disconnect
		if (wfi->force_all_disconnect == TRUE)
		{
			DEBUG_WARN("Forcing Disconnect -> ");
			break;
		}

		/* FIXME: we should wait on this, instead of calling it every time */
		if (WTSVirtualChannelManagerCheckFileDescriptor(context->vcm) != TRUE)
			break;
	}

	DEBUG_WARN("Client %s disconnected.\n", client->local ? "(local)" : client->hostname);

	if (WaitForSingleObject(context->updateEvent, 0) == 0)
	{
		ResetEvent(context->updateEvent);
		ReleaseSemaphore(wfi->updateSemaphore, 1, NULL);
	}

	wf_update_peer_deactivate(wfi, context);

	client->Disconnect(client);

	freerdp_peer_context_free(client);
	freerdp_peer_free(client);

	return 0;
}
示例#16
0
void semaphore::signal(unsigned inc)
{
    if (inc != 0) { 
	ReleaseSemaphore(s, inc, NULL);
    }
}
示例#17
0
void TerminateAllProcess()
{
    SetEvent(gTerminateAllEvent);
	ReleaseSemaphore(gWaitingSemaphore, 1, 0);
}
int  os_sem_post(os_sem_t *sem)
{
	if (!sem) return -1;
	return ReleaseSemaphore(sem->handle, 1, NULL) ? 0 : -1;
}
示例#19
0
void S9xSyncSpeed( void)
{
#ifdef NETPLAY_SUPPORT
    if (Settings.NetPlay)
    {
#if defined (NP_DEBUG) && NP_DEBUG == 2
        printf ("CLIENT: SyncSpeed @%d\n", timeGetTime () - START);
#endif
        S9xWinScanJoypads ();

		LONG prev;
        BOOL success;

	// Wait for heart beat from server
        if ((success = ReleaseSemaphore (GUI.ClientSemaphore, 1, &prev)) &&
            prev == 0)
        {
            // No heartbeats already arrived, have to wait for one.
            // Mop up the ReleaseSemaphore test above...
            WaitForSingleObject (GUI.ClientSemaphore, 0);

            // ... and then wait for the real sync-signal from the
            // client loop thread.
            NetPlay.PendingWait4Sync = WaitForSingleObject (GUI.ClientSemaphore, 100) != WAIT_OBJECT_0;
#if defined (NP_DEBUG) && NP_DEBUG == 2
            if (NetPlay.PendingWait4Sync)
                printf ("CLIENT: PendingWait4Sync1 @%d\n", timeGetTime () - START);
#endif
            IPPU.RenderThisFrame = TRUE;
            IPPU.SkippedFrames = 0;
        }
        else
        {
            if (success)
            {
                // Once for the ReleaseSemaphore above...
                WaitForSingleObject (GUI.ClientSemaphore, 0);
                if (prev == 4 && NetPlay.Waiting4EmulationThread)
                {
                    // Reached the lower behind count threshold - tell the
                    // server its safe to start sending sync pulses again.
                    NetPlay.Waiting4EmulationThread = FALSE;
                    S9xNPSendPause (FALSE);
                }

#if defined (NP_DEBUG) && NP_DEBUG == 2
                if (prev > 1)
                {
                    printf ("CLIENT: SyncSpeed prev: %d @%d\n", prev, timeGetTime () - START);
                }
#endif
            }
            else
            {
#ifdef NP_DEBUG
                printf ("*** CLIENT: SyncSpeed: Release failed @ %d\n", timeGetTime () - START);
#endif
            }

            // ... and again to mop up the already-waiting sync-signal
            NetPlay.PendingWait4Sync = WaitForSingleObject (GUI.ClientSemaphore, 200) != WAIT_OBJECT_0;
#if defined (NP_DEBUG) && NP_DEBUG == 2
            if (NetPlay.PendingWait4Sync)
                printf ("CLIENT: PendingWait4Sync2 @%d\n", timeGetTime () - START);
#endif

	    if (IPPU.SkippedFrames < NetPlay.MaxFrameSkip)
	    {
		IPPU.SkippedFrames++;
		IPPU.RenderThisFrame = FALSE;
	    }
	    else
	    {
		IPPU.RenderThisFrame = TRUE;
		IPPU.SkippedFrames = 0;
	    }
        }
        // Give up remainder of time-slice to any other waiting threads,
        // if they need any time, that is.
        Sleep (0);
        if (!NetPlay.PendingWait4Sync)
        {
            NetPlay.FrameCount++;
            S9xNPStepJoypadHistory ();
        }
    }
    else
#endif

    if (!Settings.TurboMode && Settings.SkipFrames == AUTO_FRAMERATE &&
		!GUI.AVIOut)
    {
		if (!do_frame_adjust)
		{
			IPPU.RenderThisFrame = TRUE;
			IPPU.SkippedFrames = 0;
		}
		else
		{
			if (IPPU.SkippedFrames < Settings.AutoMaxSkipFrames)
			{
				IPPU.SkippedFrames++;
				IPPU.RenderThisFrame = FALSE;
			}
			else
			{
				IPPU.RenderThisFrame = TRUE;
				IPPU.SkippedFrames = 0;
			}
		}
	}
    else
    {
	uint32 SkipFrames;
	if(Settings.TurboMode && !GUI.AVIOut)
		SkipFrames = Settings.TurboSkipFrames;
	else
		SkipFrames = (Settings.SkipFrames == AUTO_FRAMERATE) ? 0 : Settings.SkipFrames;
	if (IPPU.FrameSkip++ >= SkipFrames)
	{
	    IPPU.FrameSkip = 0;
	    IPPU.SkippedFrames = 0;
	    IPPU.RenderThisFrame = TRUE;
	}
	else
	{
	    IPPU.SkippedFrames++;
		IPPU.RenderThisFrame = GUI.AVIOut!=0;
	}
    }
}
示例#20
0
int release_semaphore(semaphore *semaphore_id)
{
    return(ReleaseSemaphore(semaphore_id, 1, NULL));
}
示例#21
0
int main(int argc, char *argv[])
{
#ifdef _WIN32
    DWORD numRead;
    DWORD numToWrite;

    if (argc != 2)
    {
        HANDLE namedPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\Pipe"),
            PIPE_ACCESS_DUPLEX,
            PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
            PIPE_UNLIMITED_INSTANCES,
            1024, 1024,
            NMPWAIT_USE_DEFAULT_WAIT,
            NULL);

        if (namedPipe == INVALID_HANDLE_VALUE)
        {
            cout << "Can't create pipe. Error. Press any key to exit " << GetLastError();
            _getch();
            exit(0);
        }

        HANDLE serverSemaphore = CreateSemaphore(NULL, 0, 1, TEXT("serverSemaphore"));
        HANDLE clientSemaphore = CreateSemaphore(NULL, 0, 1, TEXT("clientSemaphore"));

        MyProcess *clientProcess = new MyProcess(argv[0]);

        ConnectNamedPipe(namedPipe, NULL);

        WaitForSingleObject(serverSemaphore, INFINITE);

        char *buffer = NULL;
        buffer = (char *)malloc(sizeof(char) * 1024);

        printf("Server process\n");

        if (!WriteFile(namedPipe, "Ready", 1024, &numToWrite, NULL))
            return 0;

        while (1)
        {
            ReleaseSemaphore(clientSemaphore, 1, NULL);
            WaitForSingleObject(serverSemaphore, INFINITE);

            if (ReadFile(namedPipe, buffer, 1024, &numRead, NULL))
                printf("Client message: %s", buffer);

            if (!strcmp(buffer, "exit"))
            {
                CloseHandle(namedPipe);
                CloseHandle(serverSemaphore);
                free(buffer);
                return 0;
            }

            printf("\nInput message to client: ");
            fflush(stdin);
            gets_s(buffer, 1024);

            if (!WriteFile(namedPipe, buffer, 1024, &numToWrite, NULL))
                break;

            ReleaseSemaphore(clientSemaphore, 1, NULL);

            if (!strcmp(buffer, "exit"))
            {
                CloseHandle(namedPipe);
                CloseHandle(serverSemaphore);

                free(buffer);
                return 0;
            }
        }
        return 0;
    }
    else
    {
        HANDLE serverSemaphore = OpenSemaphore(EVENT_ALL_ACCESS, FALSE, TEXT("serverSemaphore"));
        HANDLE clientSemaphore = OpenSemaphore(EVENT_ALL_ACCESS, FALSE, TEXT("clientSemaphore"));

        HANDLE namedPipe = CreateFile(TEXT("\\\\.\\pipe\\Pipe"),
            GENERIC_READ | GENERIC_WRITE,
            0,
            NULL,
            OPEN_EXISTING,
            0,
            NULL);

        if (namedPipe == INVALID_HANDLE_VALUE)
        {
            printf("Can't create pipe. Error. Press any key to exit", GetLastError());
            _getch();
            exit(0);
        }

        ReleaseSemaphore(serverSemaphore, 1, NULL);

        char *buffer = NULL;
        buffer = (char *)malloc(sizeof(char) * 1024);

        printf("Client process\n");

        while (1)
        {
            WaitForSingleObject(clientSemaphore, INFINITE);

            if (ReadFile(namedPipe, buffer, 1024, &numRead, NULL))
            {
                if (!strcmp(buffer, "exit"))
                {
                    CloseHandle(clientSemaphore);
                    free(buffer);
                    return 0;
                }

                printf("Server message: %s", buffer);

                char input[1024] = { '\0' };
                cout << "\nInput message to server: ";
                fflush(stdin);
                gets_s(input, 1024);

                if (!WriteFile(namedPipe, input, 1024, &numToWrite, NULL))
                    break;

                if (!strcmp(input, "exit"))
                {
                    ReleaseSemaphore(serverSemaphore, 1, NULL);
                    CloseHandle(clientSemaphore);
                    free(buffer);
                    return 0;
                }
            }
            ReleaseSemaphore(serverSemaphore, 1, NULL);
        }
        return 0;
    }

#elif __linux__
    pid_t pid;
    key_t key = ftok("/home/", 0);

    struct sembuf serverSemaphore;
    struct sembuf clientSemaphore;
    int semaphoreId;

    int sharedMemoryId;
    char *segmentPtr;

    if (argc != 2)
    {
        switch (pid = fork())
        {
        case -1:
            printf("Can't fork process %d\n", pid);
            break;
        case 0:
            execlp("gnome-terminal", "gnome-terminal", "-x", argv[0], "1", NULL);
        default:
            if ((sharedMemoryId = shmget(key, 1024, IPC_CREAT | IPC_EXCL | 0660)) == -1)
            {
                if ((sharedMemoryId = shmget(key, 1024, 0)) == -1)
                {
                    printf("error\n");
                    exit(1);
                }
            }

            if ((segmentPtr = (char*)shmat(sharedMemoryId, NULL, 0)) == (char*)(-1))
            {
                printf("Can't attach shared memory\n");
                exit(1);
            }

            semaphoreId = semget(key, 1, 0666 | IPC_CREAT);

            if (semaphoreId < 0)
            {
                printf("Can't get semaphore\n");
                exit(EXIT_FAILURE);
            }

            if (semctl(semaphoreId, 0, SETVAL, (int)0) < 0)
            {
                printf("Can't initialize semaphore\n");
                exit(EXIT_FAILURE);
            }

            serverSemaphore.sem_num = 0;
            serverSemaphore.sem_op = 0;
            serverSemaphore.sem_flg = 0;

            printf("Server process: ");

            while (1) {
                char *message = NULL;
                message = (char*)malloc(1024 * sizeof(char));

                semop(semaphoreId, &serverSemaphore, 1);

                printf("\nInput message to client: ");
                fflush(stdin);
                cin >> message;

                strcpy(segmentPtr, message);

                serverSemaphore.sem_op = 3;
                semop(semaphoreId, &serverSemaphore, 1);

                serverSemaphore.sem_op = 0;
                semop(semaphoreId, &serverSemaphore, 1);

                if (!strcmp("exit", message))
                    return 0;

                strcpy(message, segmentPtr);
                printf("Client message: %s\n", message);
            }
            return 0;
        }
    }
    else
    {
        if ((sharedMemoryId = shmget(key, 1024, IPC_CREAT | IPC_EXCL | 0660)) == -1)
示例#22
0
RTMPPublisher::~RTMPPublisher()
{
    //OSDebugOut (TEXT("*** ~RTMPPublisher (%d queued, %d buffered)\n"), queuedPackets.Num(), bufferedPackets.Num());
    bStopping = true;

    //we're in the middle of connecting! wait for that to happen to avoid all manner of race conditions
    if (hConnectionThread)
    {
        WaitForSingleObject(hConnectionThread, INFINITE);
        OSCloseThread(hConnectionThread);
    }

    FlushBufferedPackets ();

    //OSDebugOut (TEXT("%d queued after flush\n"), queuedPackets.Num());

    if(hSendThread)
    {
        //this marks the thread to exit after current work is done
        SetEvent(hSendLoopExit);

        //this wakes up the thread
        ReleaseSemaphore(hSendSempahore, 1, NULL);

        //wait 60 sec for it to exit
        OSTerminateThread(hSendThread, 60000);
    }

    if(hSendSempahore)
        CloseHandle(hSendSempahore);

    //OSDebugOut (TEXT("*** ~RTMPPublisher hSendThread terminated (%d queued, %d buffered, %d data)\n"), queuedPackets.Num(), bufferedPackets.Num(), curDataBufferLen);

    if (hSocketThread)
    {
        //mark the socket loop to shut down after the buffer is empty
        SetEvent(hSocketLoopExit);

        //wait 60 sec for it to exit
        OSTerminateThread(hSocketThread, 60000);
    }

    //OSDebugOut (TEXT("*** ~RTMPPublisher hSocketThread terminated (%d queued, %d buffered, %d data)\n"), queuedPackets.Num(), bufferedPackets.Num(), curDataBufferLen);

    if(rtmp)
    {
        //at this point nothing should be in the buffer, flush out what remains and make it blocking
        FlushDataBuffer();

        //disable the buffered send, so RTMP_Close writes directly to the net
        rtmp->m_bCustomSend = 0;

        //ideally we need some kind of delay here, since we just dumped several seconds worth of timestamps to the network
        //at once, and Twitch at shows the offline screen as soon as the connection is severed even if there are
        //pending video frames.

        if (RTMP_IsConnected(rtmp))
            Sleep (500);    //for now
        RTMP_Close(rtmp);
    }

    if(hDataMutex)
        OSCloseMutex(hDataMutex);

    while (bufferedPackets.Num())
    {
        //this should not happen any more...
        bufferedPackets[0].data.Clear();
        bufferedPackets.Remove(0);
    }

    if (dataBuffer)
        Free(dataBuffer);

    if (hDataBufferMutex)
        OSCloseMutex(hDataBufferMutex);

    if (hBufferEvent)
        CloseHandle(hBufferEvent);

    if (hSendLoopExit)
        CloseHandle(hSendLoopExit);

    if (hSocketLoopExit)
        CloseHandle(hSocketLoopExit);

    if (hSendBacklogEvent)
        CloseHandle(hSendBacklogEvent);

    if (hBufferSpaceAvailableEvent)
        CloseHandle(hBufferSpaceAvailableEvent);

    if (hWriteEvent)
        CloseHandle(hWriteEvent);

    if(rtmp)
        RTMP_Free(rtmp);

    //--------------------------

    for(UINT i=0; i<queuedPackets.Num(); i++)
        queuedPackets[i].data.Clear();
    queuedPackets.Clear();

    double dBFrameDropPercentage = double(numBFramesDumped)/NumTotalVideoFrames()*100.0;
    double dPFrameDropPercentage = double(numPFramesDumped)/NumTotalVideoFrames()*100.0;

    Log(TEXT("Number of times waited to send: %d, Waited for a total of %d bytes"), totalTimesWaited, totalBytesWaited);

    Log(TEXT("Number of b-frames dropped: %u (%0.2g%%), Number of p-frames dropped: %u (%0.2g%%), Total %u (%0.2g%%)"),
        numBFramesDumped, dBFrameDropPercentage,
        numPFramesDumped, dPFrameDropPercentage,
        numBFramesDumped+numPFramesDumped, dBFrameDropPercentage+dPFrameDropPercentage);

    /*if(totalCalls)
        Log(TEXT("average send time: %u"), totalTime/totalCalls);*/

    strRTMPErrors.Clear();

    //--------------------------
}
示例#23
0
// Hook designed to insert the name of the dragged file into the edit control
LRESULT CALLBACK TftpClientFileNameProc (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
char szFileName [MAX_PATH];
static HANDLE hDrop;
static int    nAmount, Ark; 

    switch (message)
   {
      case WM_TIMER :
                // is previous transfer terminated
             if (WaitForSingleObject (hTftpClientSemaphore, 0) == WAIT_OBJECT_0)
                {       
                   if (! sTC.bBreak && ++Ark<nAmount)
                 {
                      DragQueryFile (hDrop, Ark, szFileName, MAX_PATH-1);
                        SetWindowText (hWnd, szFileName);
                      // ignore directories (wait for next turn)
                     if ( (GetFileAttributes (szFileName) & FILE_ATTRIBUTE_DIRECTORY) == 0)
                            SendMessage (hTftpClientWnd, WM_COMMAND, IDC_CLIENT_SEND_BUTTON, 0);
                        else   ReleaseSemaphore (hTftpClientSemaphore, 1, NULL);
                   }
                  else    // mutiple transfer either stopped or finished
                 {
                      DragFinish (hDrop);
                        KillTimer (hWnd, wParam);
                      CMsgBox (hWnd, "%d file%s fully transferred in %d block%s and %d retransmission%s", "Tftpd32", MB_OK, 
                              sTC.dwMultiFile, PLURAL(sTC.dwMultiFile),
                              sTC.dwMultiFileBlk, PLURAL(sTC.dwMultiFileBlk), 
                               sTC.nTotRetrans, PLURAL(sTC.nTotRetrans)); 
                       sTC.bBreak = sTC.bMultiFile = FALSE;
                       sTC.nTotRetrans = sTC.dwMultiFileBlk = sTC.dwMultiFile = 0 ; 
                      ReleaseSemaphore (hTftpClientSemaphore, 1, NULL);
                      break;
                 }
              }
              break;


       case WM_DROPFILES :
            hDrop = (HANDLE) wParam;
           nAmount = DragQueryFile (hDrop, -1, szFileName, MAX_PATH);
         // multi files mode : only if field Host has been filled
           if (   nAmount>=2 
             && GetDlgItemText (GetParent (hWnd), IDC_CLIENT_HOST, sTC.szHost, sizeof sTC.szHost) > 0)
          {
              if (CMsgBox (hWnd, 
                         "Upload (Put) %d files to host ?", 
                        "Tftpd32", 
                         MB_ICONQUESTION | MB_YESNOCANCEL,
                          nAmount)==IDYES)
             {
                      sTC.bMultiFile = TRUE;
                     sTC.dwMultiFileBlk=sTC.dwMultiFile=0 ; 
                        Ark=-1 ;

                      if (SetTimer (hWnd, ID_CLIENT_TRANSFER, 1000, NULL)==0)
                                CMsgBox (hWnd, "Create timer failed", "Tftpd32", MB_OK);

              } // User do not cancel MessageBox warning
         } // multi files have been dropped
         else
           {
              // only one file selected : just put its name into control 
                DragQueryFile (hDrop, 0, szFileName, MAX_PATH);
                SetWindowText (hWnd, szFileName);
              DragFinish (hDrop);
            }
          break;
     default : break;
           
   }
return CallWindowProc (fEditBoxProc, hWnd, message, wParam, lParam);
} // TftpClientFileNameProc
示例#24
0
rt_public int net_send(EIF_PSTREAM cs, char *buf, size_t size)
/* The connected socket descriptor */
/* Where data are stored */
/* Amount of data to be sent */
{
    /* Write to network */

    size_t amount;

#ifdef EIF_WINDOWS
    DWORD error;
    size_t length;
    BOOL fSuccess;
#else
    size_t length;
    int error;
    Signal_t (*oldpipe)(int);
#endif

#ifdef USE_ADD_LOG
    add_log(2, "in net_send %d bytes on fd %d", size, writefd(cs));
#endif

    REQUIRE("Valid size", size <= INT32_MAX);

#ifdef EIF_WINDOWS
    if (0 != setjmp(env)) {
        errno = EPIPE;
        fprintf (stderr, "net_send: setjmp /= 0\n");
        return -1;
    }


    ReleaseSemaphore (writeev(cs),1,NULL);
    for (length = 0; length < size; length += error) {
        amount = size - length;
        if (amount > BUFSIZ)    /* do not write more than BUFSIZ */
            amount = BUFSIZ;
        fSuccess = WriteFile(writefd(cs), buf + length, (DWORD) amount, &error, NULL);
        if (!fSuccess) {
            fprintf (stderr, "net_send: write failed. fdesc = %p, errno = %u\n", writefd(cs), (unsigned int) GetLastError());
            return -1;
        }
    }


#else  /* (not) EIF_WINDOWS */

    oldpipe = signal(SIGPIPE, broken);	/* Trap SIGPIPE within this function */
    if (0 != setjmp(env)) {
        signal(SIGPIPE, oldpipe);
        errno = EPIPE;
        printf ("net_send: setjmp /= 0\n");
        return -1;
    }


    for (length = 0; length < size; length += error) {
        amount = size - length;
        if (amount > BUFSIZ) {	/* do not write more than BUFSIZ */
            amount = BUFSIZ;
        }
        error = write(writefd(cs), buf + length, amount);
        if (error == -1) {
            if (errno != EINTR) {
#ifdef EIF_VMS
                printf ("%s: net_send: write failed. fdesc = %i, errno = %i (VMS %i)\n",
                        eifrt_vms_get_progname (NULL,0), writefd(cs), errno, vaxc$errno);
                perror (" ");
#else
                printf ("net_send: write failed. fdesc = %i, errno = %i\n", writefd(cs),  errno);
#endif
                return -1;
            }
            else
                error = 0;		/* number of bytes send */
        }
    }
    signal(SIGPIPE, oldpipe);	/* restore default handler */

#endif /* EIF_WINDOWS */
    return 0;
}
示例#25
0
int main( int argc, char *argv[] )
{ int i;
  HANDLE bgThread;
  DWORD exitCode;
  SECURITY_ATTRIBUTES semSec;

	MSEmul_UseSharedMemory(true);

#if 1
{ char test[256], *head;
	test[0] = '\0';
	head = test;
	fprintf( stderr, "appending to test[%lu] with snprintf:\n", sizeof(test) );
	do{
	  int len = strlen(test), n;
	  size_t ni = strlen("0123456789");
		fprintf( stderr, "len(test[%lu])=%d, rem. %lu added", sizeof(test), len, (size_t)(sizeof(test) - len) ); fflush(stderr);
		n = snprintf( &test[len], (size_t)(sizeof(test) - len), "0123456789" );
		head += n;
		fprintf( stderr, " %d (head[%lu]=", n, head - test ); fflush(stderr);
		if( len + n < sizeof(test) ){
			fprintf( stderr, "%c) -> %lu\n", head[0], strlen(test) );
		}
		else{
			fprintf( stderr, "!$@#) -> %lu\n", strlen(test) );
		}
	} while( strlen(test) < sizeof(test)-1 );
	fprintf( stderr, "test = %s\n", test );
}
#endif
	init_HRTime();
	tStart = HRTime_Time();
	HRTime_tic();
	{ double t0;
	  DWORD ret;
	  HANDLE hh;
		if( (hh = CreateSemaphore( NULL, 1, 0x7FFFFFFF, NULL )) ){
			t0 = HRTime_Time();
			ret = WaitForSingleObject(hh, (DWORD)(SLEEPTIMEFG*1000));
			t0 = HRTime_Time() - t0;
			fprintf( stderr, "WaitForSingleObject(hh,%lu)==%lu took %g seconds\n",
				   (DWORD)(SLEEPTIMEFG*1000), ret, t0
			);
			t0 = HRTime_Time();
			ret = WaitForSingleObject(hh, (DWORD)(SLEEPTIMEFG*1000));
			t0 = HRTime_Time() - t0;
			fprintf( stderr, "WaitForSingleObject(hh,%lu)==%lu took %g seconds\n",
				   (DWORD)(SLEEPTIMEFG*1000), ret, t0
			);
			t0 = HRTime_Time();
			ret = WaitForSingleObject(hh, 500);
			t0 = HRTime_Time() - t0;
			fprintf( stderr, "WaitForSingleObject(hh,500)==%lu took %g seconds\n",
				   ret, t0
			);
			ReleaseSemaphore(hh, 1, NULL);
			t0 = HRTime_Time();
			ret = WaitForSingleObject(hh, 500);
			t0 = HRTime_Time() - t0;
			fprintf( stderr, "WaitForSingleObject(hh,500)==%lu took %g seconds after ReleaseSemaphore()\n",
				   ret, t0
			);
			CloseHandle(hh);
		}
		else{
			fprintf( stderr, "Error creating semaphore: %s\n", winError(GetLastError()) );
		}

		ret = 0;
		YieldProcessor();
		fprintf( stderr, "sizeof(long)=%lu\n", sizeof(long) );
		_WriteBarrier();
		{ long oval, lbool;
		  void *ptr = NULL, *optr;
			oval = _InterlockedCompareExchange( (long*) &ret, 10L, 0L );
			fprintf( stderr, "_InterlockedCompareExchange(&ret==0, 10, 0) == %lu, ret==%lu\n", oval, ret );
			optr = InterlockedCompareExchangePointer( &ptr, (void*) fprintf, NULL );
			fprintf( stderr, "InterlockedCompareExchangePointer(&ptr==NULL, fprintf==%p, NULL) == %p, ret==%p\n",
				   fprintf, optr, ptr );
			_InterlockedIncrement( (long*) &ret );
			fprintf( stderr, "_InterlockedIncrement(&ret) ret=%lu\n", ret );
			_InterlockedDecrement( (long*) &ret );
			fprintf( stderr, "_InterlockedDecrement(&ret) ret=%lu\n", ret );
			_ReadWriteBarrier();
			lbool = false;
			_InterlockedSetTrue(&lbool);
			fprintf( stderr, "lbool = %ld\n", lbool );
			_InterlockedSetTrue(&lbool);
			fprintf( stderr, "lbool = %ld\n", lbool );
			_InterlockedSetFalse(&lbool);
			fprintf( stderr, "lbool = %ld\n", lbool );
		}
	}
#ifdef DEBUG
	{ CSEScopedLock *scope = ObtainCSEScopedLock(NULL);
		fprintf( stderr, "NULL testscope %p:locked==%u\n", scope, IsCSEScopeLocked(scope) );
		scope = ReleaseCSEScopedLock(scope);
	}
#endif

	csex = CreateCSEHandle(4000);
	if( !csex ){
		fprintf( stderr, "Failure creating CSEHandle\n" );
		exit(1);
	}
	else{
		fprintf( stderr, "Created a '%s' CSEHandle with spinMax==%lu\n", CSEHandleInfo(csex), csex->spinMax );
	}

	fprintf( stderr, "GetCurrentThread() = 0x%p\n", GetCurrentThread() ); Sleep(5);
	fprintf( stderr, "GetCurrentThread() = 0x%p\n", GetCurrentThread() ); Sleep(5);
	fprintf( stderr, "GetCurrentThread() = 0x%p\n", GetCurrentThread() ); Sleep(5);

	fputs( "\n", stderr );
	if( (bgThread = CreateThread( NULL, 0, bgThreadSleeper, NULL, CREATE_SUSPENDED, NULL )) ){
	  unsigned long ret;
	  double tEnd;
		fprintf( stderr, ">%lx t=%g will start %lx and WaitForSingleObject on it (should take 5s)\n",
			   GetCurrentThreadId(), HRTime_Time() - tStart, GetThreadId(bgThread) );
		ResumeThread(bgThread);
//		Sleep(1);
		ret = WaitForSingleObject( bgThread, 1500 ); tEnd = HRTime_Time();
		GetExitCodeThread( bgThread, &exitCode );
		fprintf( stderr, ">%lx WaitForSingleObject(bgThread,1500)=%lu exitCode=%ld at t=%g\n",
			   GetCurrentThreadId(), ret, exitCode, tEnd - tStart );
		ret = WaitForSingleObject( bgThread, 10000 ); tEnd = HRTime_Time();
		GetExitCodeThread( bgThread, &exitCode );
		fprintf( stderr, ">%lx WaitForSingleObject(bgThread,10000)=%lu exitCode=%ld at t=%g\n",
			   GetCurrentThreadId(), ret, exitCode, tEnd - tStart );
		CloseHandle(bgThread);
	}
	fputs( "\n", stderr );
	if( (nudgeEvent = CreateEvent( NULL, false, false, NULL )) ){
		if( (bgThread = CreateThread( NULL, 0, bgThread2Nudge, NULL, 0, NULL )) ){
		  unsigned long ret;
		  double tEnd;
			Sleep(1000);
			fprintf( stderr, ">%lx t=%g SetEvent(nudgeEvent) = %d; sleep(1ms) and then wait for return nudge\n", GetCurrentThreadId(), HRTime_Time() - tStart, SetEvent(nudgeEvent) );
			Sleep(1);
			ret = WaitForSingleObject( nudgeEvent, INFINITE ); tEnd = HRTime_Time();
			fprintf( stderr, ">%lx WaitForSingleObject( nudgeEvent, INFINITE ) = %lu at t=%g\n",
				   GetCurrentThreadId(), ret, tEnd - tStart );
			ret = WaitForSingleObject( bgThread, 5000 ); tEnd = HRTime_Time();
			GetExitCodeThread( bgThread, &exitCode );
			fprintf( stderr, ">%lx WaitForSingleObject(bgThread,5000)=%lu exitCode=%ld at t=%g\n",
				   GetCurrentThreadId(), ret, exitCode, tEnd - tStart );
			CloseHandle(bgThread);
		}
		CloseHandle(nudgeEvent);
	}
	fputs( "\n", stderr );
	semSec.nLength = sizeof(SECURITY_ATTRIBUTES);
	semSec.lpSecurityDescriptor = NULL;
	semSec.bInheritHandle = true;
	// semSec does not actually need to be used:
	if( (nudgeEvent = CreateSemaphore( &semSec, 0, 0x7FFFFFFF, (char*) "cseSem" )) ){
		if( (bgThread = CreateThread( NULL, 0, bgThread4SemTest, NULL, 0, NULL )) ){
		  unsigned long ret;
		  double tEnd;
			Sleep(1000);
			fprintf( stderr, ">%lx t=%g ReleaseSemaphore(nudgeEvent,1,NULL) = %d; sleep(1ms) and then wait for return nudge\n",
				   GetCurrentThreadId(), HRTime_Time() - tStart, ReleaseSemaphore(nudgeEvent, 1, NULL) );
			Sleep(1);
			ret = WaitForSingleObject( nudgeEvent, INFINITE ); tEnd = HRTime_Time();
			fprintf( stderr, ">%lx WaitForSingleObject( nudgeEvent, INFINITE ) = %lu at t=%g\n",
				   GetCurrentThreadId(), ret, tEnd - tStart );
			ret = WaitForSingleObject( bgThread, 5000 ); tEnd = HRTime_Time();
			GetExitCodeThread( bgThread, &exitCode );
			fprintf( stderr, ">%lx WaitForSingleObject(bgThread,5000)=%lu exitCode=%ld at t=%g\n",
				   GetCurrentThreadId(), ret, exitCode, tEnd - tStart );
			CloseHandle(bgThread);
		}
		CloseHandle(nudgeEvent);
	}
	fputs( "\n", stderr );
	if( (bgThread = CreateThread( NULL, 0, bgCSEXaccess, NULL, CREATE_SUSPENDED, NULL )) ){
		fprintf( stderr, "csex is %slocked\n", (IsCSEHandleLocked(csex))? "" : "not " );
		SetThreadPriority( bgThread, GetThreadPriority(GetCurrentThread()) );
		fprintf( stderr, "GetThreadPriority(GetCurrentThread()) = %d\n", GetThreadPriority(GetCurrentThread()) );
		ResumeThread(bgThread);
		i = 0;
		fprintf( stderr, "entering main csex locking loop at t=%gs\n", HRTime_toc() );
		while( i < 5 ){
		  double t0, t1;

			if( IsCSEHandleLocked(csex) ){
				fprintf( stderr, "\tmain loop waiting for csex lock\n" );
			}
			t0 = HRTime_toc();
			{
#ifdef LOCKSCOPEFG
			  CSEScopedLock *scope = ObtainCSEScopedLock(csex);
#else
			  unsigned char unlock = LockCSEHandle(csex);
#endif
				t1 = HRTime_toc();
				i += 1;
				fprintf( stderr, "> got csex lock #%d=%d at t=%g after %gs; starting %g s wait\n",
						i, IsCSEHandleLocked(csex), t1, t1-t0, SLEEPTIMEFG ); fflush(stderr);
#ifdef BUSYSLEEPING
				MMSleep(SLEEPTIMEFG);
#else
				do{
					t1 = HRTime_toc();
				} while (t1-t0 < SLEEPTIMEFG);
#endif
				fprintf( stderr, "\tmain loop wait #%d ended at t=%gs; csex lock=%d\n",
					i, HRTime_toc(), IsCSEHandleLocked(csex) ); fflush(stderr);
#ifndef LOCKSCOPEFG
				UnlockCSEHandle( csex, unlock );
#else
				scope = ReleaseCSEScopedLock(scope);
#endif
			}
			// just to give the other thread a chance to get a lock:
			Sleep(1);
		}
		fprintf( stderr, "exiting main csex locking loop at t=%gs\n", HRTime_toc() );
		_InterlockedSetFalse(&bgRun);
		WaitForSingleObject( bgThread, 5000 );
		CloseHandle(bgThread);
		fprintf( stderr, "Background loop finished at t=%gs\n", HRTime_toc() );
	}
	else{
		fprintf( stderr, "Failure creating bgCSEXaccess thread\n" );
	}
	DeleteCSEHandle(csex);
	ASSERT(1);
	ASSERT(0);
	exit(0);
}
示例#26
0
void Semaphore::signal() {
  if (!ReleaseSemaphore(m_sem, 1, NULL)) {
    throwLastErrorOnSysCallException(_T("ReleaseSemaphore"));
  }
}
void qemu_sem_post(QemuSemaphore *sem)
{
    ReleaseSemaphore(sem->sema, 1, NULL);
}
示例#28
0
void Semaphore::Post(int count) {
    if (!ReleaseSemaphore(handle, count, NULL))
        Severe("Error from ReleaseSemaphore: %d", GetLastError());
}
示例#29
0
int
sem_post_multiple (sem_t * sem, int count)
     /*
      * ------------------------------------------------------
      * DOCPUBLIC
      *      This function posts multiple wakeups to a semaphore.
      *
      * PARAMETERS
      *      sem
      *              pointer to an instance of sem_t
      *
      *      count
      *              counter, must be greater than zero.
      *
      * DESCRIPTION
      *      This function posts multiple wakeups to a semaphore. If there
      *      are waiting threads (or processes), n <= count are awakened;
      *      the semaphore value is incremented by count - n.
      *
      * RESULTS
      *              0               successfully posted semaphore,
      *              -1              failed, error in errno
      * ERRNO
      *              EINVAL          'sem' is not a valid semaphore
      *                              or count is less than or equal to zero.
      *
      * ------------------------------------------------------
      */
{
  int result = 0;
#ifndef NEED_SEM
  long waiters;
  sem_t s = *sem;
#endif

  if (s == NULL || count <= 0)
    {
      result = EINVAL;
    }

#ifdef NEED_SEM

  else if (!ptw32_increase_semaphore (sem, count))
    {
      result = EINVAL;
    }

#else /* NEED_SEM */

  else if ((result = pthread_mutex_lock (&s->lock)) == 0)
    {
      waiters = -s->value;
      s->value += count;
      if (waiters > 0)
        {
          if (!ReleaseSemaphore (s->sem,  (waiters<=count)?waiters:count, 0))
            {
              result = EINVAL;
            }
        }
      (void) pthread_mutex_unlock (&s->lock);
    }

#endif /* NEED_SEM */

  if (result != 0)
    {
      errno = result;
      return -1;
    }

  return 0;

}				/* sem_post_multiple */
示例#30
0
DWORD WINAPI preloaderIcon(LPVOID param)
{
	bool processed = false;
	DWORD waitFor;
	SHFILEINFO tSHFileInfo;
	iconLoader* loader = (iconLoader*)param;

	ZeroMemory(&tSHFileInfo, sizeof(tSHFileInfo));

	// Load Icon
	//
	wchar_t* pos = 0;
	if( loader->ext == NULL && (wcsstr(loader->filename, L".exe") != NULL || wcsstr(loader->filename, L".dll") != NULL) )
	{
		pos = wcschr(loader->filename, L',');
	}
	if( pos > 0 )
	{
		wchar_t icoPath[512];
		int i = 0;
		wcsncpy_s( icoPath, 512, loader->filename, size_t(pos - loader->filename) );
		i = _wtoi( &pos[1] );
		ExtractIconEx( icoPath, i, NULL, &tSHFileInfo.hIcon, 1 );
	}
	else
	{
		DWORD attribs = GetFileAttributes(loader->filename);
		if( attribs == (DWORD)-1 )
		{
			processed = true;
		}
		else
		{
			if( !wcscmp(loader->filename, L"/") || (attribs & FILE_ATTRIBUTE_DIRECTORY) )
			{
				SHGetFileInfo(loader->filename, FILE_ATTRIBUTE_DIRECTORY, &tSHFileInfo, sizeof(tSHFileInfo), SHGFI_ICON | SHGFI_USEFILEATTRIBUTES | SHGFI_SMALLICON);
			}
			else
			{
				SHGetFileInfo(loader->filename , 0, &tSHFileInfo, sizeof(tSHFileInfo), SHGFI_ICON | SHGFI_SMALLICON);
			}
		}
	}

	while(!processed)
	{
		waitFor = WaitForSingleObject( loader->semaphore, 100L );
		if( waitFor == WAIT_OBJECT_0 )
		{
			// Set the icon
			loader->icon = tSHFileInfo.hIcon;

			processed = true;

			// Call redraw
			//
			for(refreshParams::iterator i = loader->refreshs->begin(); i != loader->refreshs->end(); i++)
			{
				PostMessageW(g_hwndMain, WM_DRAWITEM, (*i)->lParam, (*i)->wParam);
				free( (*i) );
			}
			delete loader->refreshs;
			loader->refreshs = NULL;
			loader->thread = NULL;

			ReleaseSemaphore( loader->semaphore, 1, NULL );
			CloseHandle( loader->semaphore );
			loader->semaphore = NULL;
		}
		else
		{
			if( loader->semaphore == NULL )
				processed = true;
		}
	}
	if( loader->semaphore != NULL )
	{
		ReleaseSemaphore( loader->semaphore, 1, NULL );
		CloseHandle( loader->semaphore );
		loader->semaphore = NULL;
	}
	if( loader->refreshs != NULL )
	{
		for(refreshParams::iterator i = loader->refreshs->begin(); i != loader->refreshs->end(); i++)
		{
			free( (*i) );
		}
		delete loader->refreshs;
		loader->refreshs = NULL;
	}
	loader->thread = NULL;
	return TRUE;
}