• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C++ sem_wait函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中sem_wait函数的典型用法代码示例。如果您正苦于以下问题:C++ sem_wait函数的具体用法?C++ sem_wait怎么用?C++ sem_wait使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了sem_wait函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: sem_wait

Mail* Mailbox::Pend() {
    sem_wait(&semInside);
    Mail* mail = mailBuffer.front();
    mailBuffer.pop();
    return mail;
}
开发者ID:AfkMan,项目名称:NeeTechLibrary,代码行数:6,代码来源:Mailbox.cpp


示例2: main

int main(int argc, char *argv[]){
	
	//Creates semaphore that will be used to avoid writting at the same time as other threads
	sem_t *semaphore = sem_open(SEM, O_CREAT ,0660,1);
	
	//Checks for number of arguments
	if(argc != 3)
	{
		printf("Invalid number of arguments!\n Correct usage: parque <int num_Lugares> <int open_time>\nn");
		perror("Argument Number");
		exit(1);
	}

	//converts inputs from string to int and saves in global variable
	n_lugares = atoi(argv[1]);
	t_abertura = atoi(argv[2]);

	//checks if inputs are valid
	if(n_lugares < 1){
		printf("error: n_lugares < 1");
		perror("n_lugares must be an integer bigger than 0");
		exit(1);
	}
	if(t_abertura < 1){
		printf("error: t_abertura < 1");
		perror("t_abertura must be an integer bigger than 0");
		exit(1);
	}

	time_t start, current;
	//Saves the starting time
	time(&start);

	//Creates fifos for each entrance
	mkfifo("fifoN",FIFO_PERMISSIONS);
	mkfifo("fifoS",FIFO_PERMISSIONS);
	mkfifo("fifoE",FIFO_PERMISSIONS);
	mkfifo("fifoW",FIFO_PERMISSIONS);

	
	//A char for each of the entrances, used in creating controller threads
	char NN = 'N';
	char SS = 'S';
	char EE = 'E';
	char WW = 'W';
	
	//Creates the parque.log file
	pLog = fopen("parque.log", "w");
	
	//Prints the log header
	fprintf(pLog, "  t(ticks) ;   nLug    ;   id_viat ;   observs\n");

	
	//Prepares thread variable and attributes
	pthread_t t;
	pthread_attr_t attr;
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);


	//Creates thread 'controlador' North
	if((pthread_create(&t, &attr, &controlador, &NN)) != 0){
		printf("Error creating new 'controlador' thread\n");
		perror("Creating thread");
		exit(THREAD_EXIT);
	}

	//Creates thread 'controlador' South
	if((pthread_create(&t, &attr, &controlador, &SS)) != 0){
		printf("Error creating new 'controlador' thread\n");
		perror("Creating thread");
		exit(THREAD_EXIT);
	}

	//Creates thread 'controlador' East
	if((pthread_create(&t, &attr, &controlador, &EE)) != 0){
		printf("Error creating new 'controlador' thread\n");
		perror("Creating thread");
		exit(THREAD_EXIT);
	}

	//Creates thread 'controlador' West
	if((pthread_create(&t, &attr, &controlador, &WW)) != 0){
		printf("Error creating new 'controlador' thread\n");
		perror("Creating thread");
		exit(THREAD_EXIT);
	}
	
	//Sleeps for the duration that it is supposed to be opened
	sleep(t_abertura);
	
	//Only this or a thread can write to the controller's fifo at any given time
	sem_wait(semaphore);
	
	//Opens controllers' fifos for writing
	int fdN = open("fifoN", O_WRONLY);
	int fdS = open("fifoS", O_WRONLY);
	int fdE = open("fifoE", O_WRONLY);
	int fdW = open("fifoW", O_WRONLY);
	
//.........这里部分代码省略.........
开发者ID:pedro-c,项目名称:SOPE-PROJ-FEUP,代码行数:101,代码来源:parque.c


示例3: UpnpChannelManager_RegisterChannel

// Called by the UPnP Remote I/O Microstack
// Implements the RegisterChannel call, lets the CP register a new RIO channels for a
// certain amont of time. The CP must re-register the channel from time-to-time to
// prevent the channel from expiring.
void UpnpChannelManager_RegisterChannel(void* upnptoken,char* Name,char* PeerConnection,int Timeout)
{
	// Scan the channel list for an existing channel
	struct RemoteIOChannel* channelindex = RIO->ChannelList;
	struct RemoteIOChannel* newchannel;

	printf("RegisterChannel (%d): %s\r\n",Timeout,Name);

	if (PeerConnection == NULL)
	{
		if (upnptoken != NULL) UpnpResponse_Error(upnptoken,800,"Invalid PeerConnection URI");
		return;
	}

	sem_wait(&RemoteIOLock);

	while (channelindex != NULL)
	{
		// Look for a match
		if (strcmp(channelindex->uri,PeerConnection) == 0) break;
		channelindex = channelindex->next;
	}

	if (channelindex != NULL)
	{
		// Update the expiration time
		ILibLifeTime_Remove(RIO->RIOLifeTime,channelindex);
		#ifdef _WIN32_WCE
			channelindex->expiration = (GetTickCount() / 1000) + Timeout;
			ILibLifeTime_Add(RIO->RIOLifeTime,channelindex,Timeout,&RemoteIO_ChannelExpireSink, NULL);
		#elif WIN32
			channelindex->expiration = (GetTickCount() / 1000) + Timeout;
			ILibLifeTime_Add(RIO->RIOLifeTime,channelindex,Timeout,&RemoteIO_ChannelExpireSink, NULL);
		#elif _POSIX
			gettimeofday(&(channelindex->expiration),NULL);
			(channelindex->expiration).tv_sec += (int)Timeout;
			ILibLifeTime_Add(RIO->RIOLifeTime,channelindex,Timeout,&RemoteIO_ChannelExpireSink, NULL);
		#endif
	}
	else
	{
		// Add a new channel to the channel list
		newchannel = (struct RemoteIOChannel*)RIO_MALLOC(sizeof(struct RemoteIOChannel));
		newchannel->name = (char*)RIO_MALLOC(strlen(Name)+1);
		strcpy(newchannel->name,Name);
		newchannel->uri = (char*)RIO_MALLOC(strlen(PeerConnection)+1);
		strcpy(newchannel->uri,PeerConnection);
		#ifdef _WIN32_WCE
			newchannel->expiration = (GetTickCount() / 1000) + Timeout;
			ILibLifeTime_Add(RIO->RIOLifeTime,newchannel,Timeout,&RemoteIO_ChannelExpireSink, NULL);
		#elif WIN32
			newchannel->expiration = (GetTickCount() / 1000) + Timeout;
			ILibLifeTime_Add(RIO->RIOLifeTime,newchannel,Timeout,&RemoteIO_ChannelExpireSink, NULL);
		#elif _POSIX
			gettimeofday(&(newchannel->expiration),NULL);
			(newchannel->expiration).tv_sec += (int)Timeout;
			ILibLifeTime_Add(RIO->RIOLifeTime,newchannel,Timeout,&RemoteIO_ChannelExpireSink, NULL);
		#endif
		newchannel->next = RIO->ChannelList;
		RIO->ChannelList = newchannel;

		// Set the channels to be evented
		if (RIO->EventModerationSet == 0)
		{
			ILibLifeTime_Add(RIO->RIOLifeTime,NULL,2,&RemoteIO_EventChannelList, NULL);
			RIO->EventModerationSet = 1;
		}
	}

	UpnpResponse_ChannelManager_RegisterChannel(upnptoken);

	sem_post(&RemoteIOLock);
}
开发者ID:optman,项目名称:upnpstack,代码行数:77,代码来源:RemoteIOClientStack.c


示例4: escalonar

void escalonar(int tempoExec){

	int i=0;

	sem_wait(&semEscalonador);
	if(tempoExec > 0){
		printf("#-----------------------------------------------------------------------------------------#\n");
		printf("#-----------------------------------------------------------------------------------------#\n\n");
		if(executando == 0){
			printf("Iniciando execução \n");
			executando = 1;

			switch(Dados.Prioridade){
				case 1:
					Fila1 = Remove(Fila1);
					emExecucao = Insere(emExecucao,Dados.PID,Dados.Prioridade);

					printf("Executando processo por 100 ut \n");
					for(i=0;i<3;i++){
						printf("Executando processo ... \n");
						sleep(2);
					}
					tempoExec = tempoExec - 100;
					emExecucao = Remove(emExecucao);

					if(tempoExec > 0){
						trataInterrupcao(1);
					}else{
						trataInterrupcao(3);
					}

					break;

				case 2:
					Fila2 = Remove(Fila2);
					emExecucao = Insere(emExecucao,Dados.PID,Dados.Prioridade);

					printf("Executando processo por 200 ut \n");
					for(i=0;i<3;i++){
						printf("Executando processo ... \n");
						sleep(2);
					}
					tempoExec = tempoExec - 200;
					emExecucao = Remove(emExecucao);

					if(tempoExec > 0){
						trataInterrupcao(1);
					}else{
						trataInterrupcao(3);
				    }

					break;

				case 3:
					Fila3 = Remove(Fila3);
					emExecucao = Insere(emExecucao,Dados.PID,Dados.Prioridade);

					printf("Executando processo por 400 ut \n");
					for(i=0;i<3;i++){
						printf("Executando processo ... \n");
						sleep(2);
					}
					tempoExec = tempoExec - 400;
					emExecucao = Remove(emExecucao);

					if(tempoExec > 0){
						trataInterrupcao(1);
					}else{
						trataInterrupcao(3);
					}

					break;

				case 4:
					Fila2 = Remove(Fila2);
					emExecucao = Insere(emExecucao,Dados.PID,Dados.Prioridade);

					printf("Executando processo por 600 ut \n");
					for(i=0;i<3;i++){
						printf("Executando processo ... \n");
						sleep(2);
					}
					tempoExec = tempoExec - 600;
					emExecucao = Remove(emExecucao);

					if(tempoExec > 0){
						trataInterrupcao(1);
					}else{
						trataInterrupcao(3);
					}

					break;

				case 5:
					Fila2 = Remove(Fila2);
					emExecucao = Insere(emExecucao,Dados.PID,Dados.Prioridade);

					printf("Executando processo por 100 ut \n");
					for(i=0;i<3;i++){
						printf("Executando processo ... \n");
//.........这里部分代码省略.........
开发者ID:renanalboy,项目名称:Trabalhos-Graduacao,代码行数:101,代码来源:nucleo.c


示例5: main

void main (int argc, char *argv[])
{
  int numprocs = 0;               // Used to store number of processes to create
  int i;                          // Loop index variable
  missile_code *mc;               // Used to get address of shared memory page
  uint32 h_mem;                   // Used to hold handle to shared memory page
  sem_t s_procs_completed;        // Semaphore used to wait until all spawned processes have completed
  char h_mem_str[10];             // Used as command-line argument to pass mem_handle to new processes
  char s_procs_completed_str[10]; // Used as command-line argument to pass page_mapped handle to new processes

  if (argc != 2) {
    Printf("Usage: "); Printf(argv[0]); Printf(" <number of processes to create>\n");
    Exit();
  }

  // Convert string from ascii command line argument to integer number
  numprocs = dstrtol(argv[1], NULL, 10); // the "10" means base 10
  Printf("Creating %d processes\n", numprocs);

  // Allocate space for a shared memory page, which is exactly 64KB
  // Note that it doesn't matter how much memory we actually need: we 
  // always get 64KB
  if ((h_mem = shmget()) == 0) {
    Printf("ERROR: could not allocate shared memory page in "); Printf(argv[0]); Printf(", exiting...\n");
    Exit();
  }

  // Map shared memory page into this process's memory space
  if ((mc = (missile_code *)shmat(h_mem)) == NULL) {
    Printf("Could not map the shared page to virtual address in "); Printf(argv[0]); Printf(", exiting..\n");
    Exit();
  }

  // Put some values in the shared memory, to be read by other processes
  mc->numprocs = numprocs;
  mc->really_important_char = 'A';

  // Create semaphore to not exit this process until all other processes 
  // have signalled that they are complete.  To do this, we will initialize
  // the semaphore to (-1) * (number of signals), where "number of signals"
  // should be equal to the number of processes we're spawning - 1.  Once 
  // each of the processes has signaled, the semaphore should be back to
  // zero and the final sem_wait below will return.
  if ((s_procs_completed = sem_create(-(numprocs-1))) == SYNC_FAIL) {
    Printf("Bad sem_create in "); Printf(argv[0]); Printf("\n");
    Exit();
  }

  // Setup the command-line arguments for the new process.  We're going to
  // pass the handles to the shared memory page and the semaphore as strings
  // on the command line, so we must first convert them from ints to strings.
  ditoa(h_mem, h_mem_str);
  ditoa(s_procs_completed, s_procs_completed_str);

  // Now we can create the processes.  Note that you MUST end your call to
  // process_create with a NULL argument so that the operating system
  // knows how many arguments you are sending.
  for(i=0; i<numprocs; i++) {
    Printf("h_mem_str : %s semaphore_str : %s", h_mem_str, s_procs_completed_str);
    
    process_create(FILENAME_TO_RUN, h_mem_str, s_procs_completed_str, NULL);
    Printf("Process %d created\n", i);
  }

  // And finally, wait until all spawned processes have finished.
  if (sem_wait(s_procs_completed) != SYNC_SUCCESS) {
    Printf("Bad semaphore s_procs_completed (%d) in ", s_procs_completed); Printf(argv[0]); Printf("\n");
    Exit();
  }
  Printf("All other processes completed, exiting main process.\n");
}
开发者ID:aggarw13,项目名称:ECE469_Operating_Systems,代码行数:71,代码来源:makeprocs.c


示例6: main


//.........这里部分代码省略.........
		Error(1); // Error has occurred
	}

	// Opens shared memory between two processes

	shmid1 = shm_get(900001, (void*) &BufferA, 22);

	// Opens shared memory between two processes

	shmid2 = shm_get(900002, (void*) &BufferB, 69);


	// Create duplicate processes and give them code for processes X and Y

	pX = fork();

	if (pX == 0) // process is a child
	{
		execv("ProcX", arg);
	}

	pY = fork();

	if (pY == 0) // process is a child
	{
		execv("ProcY", arg);
	}


	// Synchronize with ProcX and ProcY

	temp = sem_signal(semX);
	temp = sem_signal(semY);
	temp = sem_wait(semZ);
	temp = sem_wait(semZ);


	// Take out items from buffers when elements exist

	counter = 1;
	input = 0;

	while (counter <= 260)
	{
		// Wait until both of the buffers have been filled

		temp = sem_wait(CSZ);
		temp = sem_wait(CSZ);

		// Remove one item from BufferA when one exists

		temp = sem_wait(bufAFilled);

		c1 = BufferA[input*2];
		c2 = BufferA[input*2+1];

		printf("+ %c%c +", c1, c2);

		temp = sem_signal(bufAEmpty);

		// Remove one item from BufferB when one exists

		temp = sem_wait(bufBFilled);

		c1 = BufferB[input*3];
		c2 = BufferB[input*3+1];
开发者ID:stevenharman,项目名称:osu-cis,代码行数:67,代码来源:Lab3+-+ProcZ.c


示例7: rping_test_client

static int rping_test_client(struct rping_cb *cb)
{
	int ping, start, cc, i, ret = 0;
	struct ibv_send_wr *bad_wr;
	unsigned char c;

	start = 65;
	for (ping = 0; !cb->count || ping < cb->count; ping++) {
		cb->state = RDMA_READ_ADV;

		/* Put some ascii text in the buffer. */
		cc = sprintf(cb->start_buf, RPING_MSG_FMT, ping);
		for (i = cc, c = start; i < cb->size; i++) {
			cb->start_buf[i] = c;
			c++;
			if (c > 122)
				c = 65;
		}
		start++;
		if (start > 122)
			start = 65;
		cb->start_buf[cb->size - 1] = 0;

		rping_format_send(cb, cb->start_buf, cb->start_mr);
		ret = ibv_post_send(cb->qp, &cb->sq_wr, &bad_wr);
		if (ret) {
			fprintf(stderr, "post send error %d\n", ret);
			break;
		}

		/* Wait for server to ACK */
		sem_wait(&cb->sem);
		if (cb->state != RDMA_WRITE_ADV) {
			fprintf(stderr, "wait for RDMA_WRITE_ADV state %d\n",
				cb->state);
			ret = -1;
			break;
		}

		rping_format_send(cb, cb->rdma_buf, cb->rdma_mr);
		ret = ibv_post_send(cb->qp, &cb->sq_wr, &bad_wr);
		if (ret) {
			fprintf(stderr, "post send error %d\n", ret);
			break;
		}

		/* Wait for the server to say the RDMA Write is complete. */
		sem_wait(&cb->sem);
		if (cb->state != RDMA_WRITE_COMPLETE) {
			fprintf(stderr, "wait for RDMA_WRITE_COMPLETE state %d\n",
				cb->state);
			ret = -1;
			break;
		}

		if (cb->validate)
			if (memcmp(cb->start_buf, cb->rdma_buf, cb->size)) {
				fprintf(stderr, "data mismatch!\n");
				ret = -1;
				break;
			}

		if (cb->verbose)
			printf("ping data: %s\n", cb->rdma_buf);
	}

	return ret;
}
开发者ID:2014-class,项目名称:freerouter,代码行数:68,代码来源:rping.c


示例8: s_lock

int s_lock(struct slock *sp){
    return sem_wait(sp->semp);
}
开发者ID:geassdai,项目名称:APUE,代码行数:3,代码来源:sem.c


示例9: wait

 void wait() {
   fprintf(stderr, "NandSim::wait for semaphore\n");
   sem_wait(&sem);
 }
开发者ID:chamdoo,项目名称:xbsv,代码行数:4,代码来源:testnandsim_test.cpp


示例10: main

int
main(int argc, char *argv[])
{
	const char *ethername, *ethername_ro;
	const char *serveraddr, *serveraddr_ro;
	const char *netmask;
	const char *exportpath;
	const char *imagename;
	char ifname[IFNAMSIZ], ifname_ro[IFNAMSIZ];
	void *fsarg;
	pthread_t t;
	int rv;

	/* for netcfg */
	noatf = 1;

	/* use defaults? */
	if (argc == 1) {
		ethername = "etherbus";
		ethername_ro = "etherbus_ro";
		serveraddr = "10.3.2.1";
		serveraddr_ro = "10.4.2.1";
		netmask = "255.255.255.0";
		exportpath = "/myexport";
		imagename = "ffs.img";
	} else {
		ethername = argv[1];
		ethername_ro = argv[2];
		serveraddr = argv[3];
		serveraddr_ro = argv[4];
		netmask = argv[5];
		exportpath = argv[6];
		imagename = argv[7];
	}

	rump_init();
	svc_fdset_init(SVC_FDSET_MT);

	rv = rump_pub_etfs_register("/etc/exports", "./exports", RUMP_ETFS_REG);
	if (rv) {
		errx(1, "register /etc/exports: %s", strerror(rv));
	}

	/* mini-mtree for mountd */
	static const char *const dirs[] = { "/var", "/var/run", "/var/db" };
	for (size_t i = 0; i < __arraycount(dirs); i++)
		if (rump_sys_mkdir(dirs[i], 0777) == -1)
			err(1, "can't mkdir `%s'", dirs[i]);

	if (ffs_fstest_newfs(NULL, &fsarg,
	    imagename, FSTEST_IMGSIZE, NULL) != 0)
		err(1, "newfs failed");
	if (ffs_fstest_mount(NULL, fsarg, exportpath, 0) != 0)
		err(1, "mount failed");

#if 0
	/*
	 * Serve from host instead of dedicated mount?
	 * THIS IS MORE EVIL THAN MURRAY THE DEMONIC TALKING SKULL!
	 */

	if (ukfs_modload("/usr/lib/librumpfs_syspuffs.so") < 1)
		errx(1, "modload");

	mount_syspuffs_parseargs(__arraycount(pnullarg), pnullarg,
	    &args, &mntflags, canon_dev, canon_dir);
	if ((ukfs = ukfs_mount(MOUNT_PUFFS, "/", UKFS_DEFAULTMP, MNT_RDONLY,
	    &args, sizeof(args))) == NULL)
		err(1, "mount");

	if (ukfs_modload("/usr/lib/librumpfs_nfsserver.so") < 1)
		errx(1, "modload");
#endif

	if (sem_init(&gensem, 1, 0) == -1)
		err(1, "gensem init");

	/* create interface */
	netcfg_rump_makeshmif(ethername, ifname);
	netcfg_rump_if(ifname, serveraddr, netmask);

	netcfg_rump_makeshmif(ethername_ro, ifname_ro);
	netcfg_rump_if(ifname_ro, serveraddr_ro, netmask);

	/*
	 * No syslogging, thanks.
	 * XXX: "0" does not modify the mask, so pick something
	 * which is unlikely to cause any logging
	 */
	setlogmask(0x10000000);

	if (pthread_create(&t, NULL, rpcbind_main, NULL) == -1)
		err(1, "rpcbind");
	sem_wait(&gensem);

	if (pthread_create(&t, NULL, mountd_main, NULL) == -1)
		err(1, "mountd");
	sem_wait(&gensem);

	rv = 0;
//.........这里部分代码省略.........
开发者ID:2trill2spill,项目名称:freebsd,代码行数:101,代码来源:rumpnfsd.c


示例11: begin_write

void begin_write(struct lectred* l) {
	sem_wait(&(l->ecriture));
}
开发者ID:LilyOfTheWest,项目名称:M1-Info,代码行数:3,代码来源:exo2_2.c


示例12: AcpiOsWaitSemaphore

ACPI_STATUS
AcpiOsWaitSemaphore (
    ACPI_HANDLE         Handle,
    UINT32              Units,
    UINT16              Timeout)
{
    ACPI_STATUS         Status = AE_OK;

#if 0
    if (!Sem)
    {
        return (AE_BAD_PARAMETER);
    }

    switch (Timeout)
    {
    /*
     * No Wait:
     * --------
     * A zero timeout value indicates that we shouldn't wait - just
     * acquire the semaphore if available otherwise return AE_TIME
     * (a.k.a. 'would block').
     */
    case 0:

        if (sem_trywait(Sem) == -1)
        {
            Status = (AE_TIME);
        }
        break;

    /* Wait Indefinitely */

    case ACPI_WAIT_FOREVER:

        if (sem_wait (Sem))
        {
            Status = (AE_TIME);
        }
        break;

    /* Wait with Timeout */

    default:

        T.tv_sec = Timeout / 1000;
        T.tv_nsec = (Timeout - (T.tv_sec * 1000)) * 1000000;

#ifdef ACPI_USE_ALTERNATE_TIMEOUT
        /*
         * Alternate timeout mechanism for environments where
         * sem_timedwait is not available or does not work properly.
         */
        while (Timeout)
        {
            if (sem_trywait (Sem) == 0)
            {
                /* Got the semaphore */
                return (AE_OK);
            }
            usleep (1000);  /* one millisecond */
            Timeout--;
        }
        Status = (AE_TIME);
#else

        if (sem_timedwait (Sem, &T))
        {
            Status = (AE_TIME);
        }
#endif

        break;
    }
#endif

    return (Status);
}
开发者ID:Xeffyr,项目名称:KolibriOS-Mod,代码行数:78,代码来源:osunixxf.c


示例13: waiter_main

static int waiter_main(int argc, char *argv[])
{
  sigset_t set;
  struct sigaction act;
  struct sigaction oact;
  int status;

  printf("waiter_main: Waiter started\n" );

  printf("waiter_main: Unmasking signal %d\n" , WAKEUP_SIGNAL);
  (void)sigemptyset(&set);
  (void)sigaddset(&set, WAKEUP_SIGNAL);
  status = sigprocmask(SIG_UNBLOCK, &set, NULL);
  if (status != OK)
    {
      printf("waiter_main: ERROR sigprocmask failed, status=%d\n",
              status);
    }

  printf("waiter_main: Registering signal handler\n" );
  act.sa_sigaction = wakeup_action;
  act.sa_flags  = SA_SIGINFO;

  (void)sigfillset(&act.sa_mask);
  (void)sigdelset(&act.sa_mask, WAKEUP_SIGNAL);

  status = sigaction(WAKEUP_SIGNAL, &act, &oact);
  if (status != OK)
    {
      printf("waiter_main: ERROR sigaction failed, status=%d\n" , status);
    }

#ifndef SDCC
  printf("waiter_main: oact.sigaction=%p oact.sa_flags=%x oact.sa_mask=%x\n",
          oact.sa_sigaction, oact.sa_flags, oact.sa_mask);
#endif

  /* Take the semaphore */

  printf("waiter_main: Waiting on semaphore\n" );
  FFLUSH();

  status = sem_wait(&sem);
  if (status != 0)
    {
      int error = errno;
      if (error == EINTR)
        {
          printf("waiter_main: sem_wait() successfully interrupted by signal\n" );
        }
      else
        {
          printf("waiter_main: ERROR sem_wait failed, errno=%d\n" , error);
        }
    }
  else
    {
      printf("waiter_main: ERROR awakened with no error!\n" );
    }

  /* Detach the signal handler */

  act.sa_handler = SIG_DFL;
  (void)sigaction(WAKEUP_SIGNAL, &act, &oact);

  printf("waiter_main: done\n" );
  FFLUSH();

  threadexited = true;
  return 0;
}
开发者ID:hll4fork,项目名称:nuttx-apps,代码行数:71,代码来源:sighand.c


示例14: main

int main(int argc, const char *argv[]) {
	int launchErr = 0;
	
	if (argc != 2)
		launchErr = 1;
	
	if (!launchErr)
		if ( !(_max_number = atoi(argv[1])) )
			launchErr = 1;
	
	if (launchErr) {
		char progname[512];
		strcpy(progname, argv[0]);
		
		printf("Usage: %s highest_number\n", basename(progname));
		
		return 0;
	}
	
	if (create_shared_memory_region(_max_number)) {
		printf("Error while creating the shared memory region.\n");
		
		return EXIT_FAILURE;
	}
	
	sem_t *semaphore = sem_open(SEM1_NAME, O_CREAT, 0600, NULL);
	
	if (semaphore == SEM_FAILED) {
		printf("An error has occoured while creating a semaphore.\n");
		
		return EXIT_FAILURE;
	}
	
	pthread_t main_tid;
	
	pthread_create(&main_tid, NULL, main_thread, NULL);
	
	sem_wait(semaphore);
	
	if (sem_close(semaphore))
		printf("An error has occoured while closing the semaphore. Continuing anyway...");
	
	unsigned int *sharedQueue;
	
	if (get_shared_memory_region(&sharedQueue)) {
		printf("Error while accessing the shared memory region.\n");
		
		exit(EXIT_FAILURE);
	}
	
	unsigned int count = sharedQueue[0];
	
	sharedQueue[0] = 0;
	
	qsort(sharedQueue, count, sizeof(unsigned int), cq_compare);
	 
	printf("Prime Numbers up to %d (%d): ", _max_number, count);
	
	unsigned int i;
	
	for (i = 1; i < count; i++)
		printf("%d ", sharedQueue[i]);
	
	printf("\n");
	
	if (shm_unlink(SHM1_NAME)) {
		printf("An error has occoured while closing the shared memory region.");
		
		return EXIT_FAILURE;
	}
	
	return EXIT_SUCCESS;
}
开发者ID:joaodealmeida,项目名称:SOPE2,代码行数:73,代码来源:main.c


示例15: com_android_nfc_NativeNfcSecureElement_doDisconnect

static jboolean com_android_nfc_NativeNfcSecureElement_doDisconnect(JNIEnv *e, jobject o, jint handle)
{
   jclass cls;
   jfieldID f;
   NFCSTATUS status;
   jboolean result = JNI_FALSE;
   phLibNfc_SE_List_t SE_List[PHLIBNFC_MAXNO_OF_SE];
   uint8_t i, No_SE = PHLIBNFC_MAXNO_OF_SE, SmartMX_index=0, SmartMX_detected = 0;
   uint32_t SmartMX_Handle;
   struct nfc_jni_callback_data cb_data;
   phNfc_sData_t    InParam;
   phNfc_sData_t    OutParam;
   uint8_t          Output_Buff[10];
   uint8_t          GpioGetValue[3] = {0x00, 0xF8, 0x2B};
   uint8_t          GpioSetValue[4];
   uint8_t          gpioValue;

   /* Create the local semaphore */
   if (!nfc_cb_data_init(&cb_data, NULL))
   {
      goto clean_and_return;
   }

   TRACE("Close Secure element function ");

   CONCURRENCY_LOCK();
   /* Disconnect */
   TRACE("Disconnecting from SMX (handle = 0x%x)", handle);
   REENTRANCE_LOCK();
   status = phLibNfc_RemoteDev_Disconnect(handle, 
                                          NFC_SMARTMX_RELEASE,
                                          com_android_nfc_jni_disconnect_callback,
                                          (void *)&cb_data);
   REENTRANCE_UNLOCK();
   if(status != NFCSTATUS_PENDING)
   {
      LOGE("phLibNfc_RemoteDev_Disconnect(SMX) returned 0x%04x[%s]", status, nfc_jni_get_status_name(status));
      goto clean_and_return;
   }
   TRACE("phLibNfc_RemoteDev_Disconnect(SMX) returned 0x%04x[%s]", status, nfc_jni_get_status_name(status));

   /* Wait for callback response */
   if(sem_wait(&cb_data.sem))
   {
       goto clean_and_return;
   }

   /* Disconnect Status */
   if(cb_data.status != NFCSTATUS_SUCCESS)
   {
     LOGE("\n> Disconnect SE ERROR \n" );
      goto clean_and_return;
   }
   CONCURRENCY_UNLOCK();

   /* Get GPIO information */
   CONCURRENCY_LOCK();
   InParam.buffer = GpioGetValue;
   InParam.length = 3;
   OutParam.buffer = Output_Buff;
   TRACE("phLibNfc_Mgt_IoCtl()- GPIO Get Value");
   REENTRANCE_LOCK();
   status = phLibNfc_Mgt_IoCtl(gHWRef,NFC_MEM_READ,&InParam, &OutParam,com_android_nfc_jni_ioctl_callback, (void *)&cb_data);
   REENTRANCE_UNLOCK();
   if(status!=NFCSTATUS_PENDING)
   {
       LOGE("IOCTL status error");
       goto clean_and_return;
   }

   /* Wait for callback response */
   if(sem_wait(&cb_data.sem))
   {
      LOGE("IOCTL semaphore error");
      goto clean_and_return;
   }

   if(cb_data.status != NFCSTATUS_SUCCESS)
   {
      LOGE("READ MEM ERROR");
      goto clean_and_return;
   }

   gpioValue = com_android_nfc_jni_ioctl_buffer->buffer[0];
   TRACE("GpioValue = Ox%02x",gpioValue);

   /* Set GPIO information */
   GpioSetValue[0] = 0x00;
   GpioSetValue[1] = 0xF8;
   GpioSetValue[2] = 0x2B;
   GpioSetValue[3] = (gpioValue & 0xBF);

   TRACE("GpioValue to be set = Ox%02x",GpioSetValue[3]);

   for(i=0;i<4;i++)
   {
       TRACE("0x%02x",GpioSetValue[i]);
   }

   InParam.buffer = GpioSetValue;
//.........这里部分代码省略.........
开发者ID:qingyue,项目名称:platform_packages,代码行数:101,代码来源:com_android_nfc_NativeNfcSecureElement.cpp


示例16: main

int
main (int argc, char *argv[])
{
  printf( "=============================================================================\n");
  printf( "\nOperations on a semaphore.\n%ld iterations\n\n",
          ITERATIONS);
  printf( "%-45s %15s %15s\n",
	    "Test",
	    "Total(msec)",
	    "average(usec)");
  printf( "-----------------------------------------------------------------------------\n");

  /*
   * Time the loop overhead so we can subtract it from the actual test times.
   */

  TESTSTART
  assert(1 == one);
  TESTSTOP

  durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs;
  overHeadMilliSecs = durationMilliSecs;


  /*
   * Now we can start the actual tests
   */
  assert((w32sema = CreateSemaphore(NULL, (long) 0, (long) ITERATIONS, NULL)) != 0);
  TESTSTART
  assert((ReleaseSemaphore(w32sema, 1, NULL),1) == one);
  TESTSTOP
  assert(CloseHandle(w32sema) != 0);

  reportTest("W32 Post with no waiters");


  assert((w32sema = CreateSemaphore(NULL, (long) ITERATIONS, (long) ITERATIONS, NULL)) != 0);
  TESTSTART
  assert((WaitForSingleObject(w32sema, INFINITE),1) == one);
  TESTSTOP
  assert(CloseHandle(w32sema) != 0);

  reportTest("W32 Wait without blocking");


  assert(sem_init(&sema, 0, 0) == 0);
  TESTSTART
  assert((sem_post(&sema),1) == one);
  TESTSTOP
  assert(sem_destroy(&sema) == 0);

  reportTest("POSIX Post with no waiters");


  assert(sem_init(&sema, 0, ITERATIONS) == 0);
  TESTSTART
  assert((sem_wait(&sema),1) == one);
  TESTSTOP
  assert(sem_destroy(&sema) == 0);

  reportTest("POSIX Wait without blocking");


  printf( "=============================================================================\n");

  /*
   * End of tests.
   */

  return 0;
}
开发者ID:AhmedAbdulSalam5,项目名称:obs-studio,代码行数:71,代码来源:benchtest5.c


示例17: com_android_nfc_NativeNfcSecureElement_doTransceive

static jbyteArray com_android_nfc_NativeNfcSecureElement_doTransceive(JNIEnv *e,
   jobject o,jint handle, jbyteArray data)
{
   uint8_t offset = 0;
   uint8_t *buf;
   uint32_t buflen;
   phLibNfc_sTransceiveInfo_t transceive_info;
   jbyteArray result = NULL;
   int res; 
   
   int tech = SecureElementTech;
   NFCSTATUS status;
   struct nfc_jni_callback_data cb_data;

   /* Create the local semaphore */
   if (!nfc_cb_data_init(&cb_data, NULL))
   {
      goto clean_and_return;
   }

   TRACE("Exchange APDU function ");
   
   CONCURRENCY_LOCK();
   
   TRACE("Secure Element tech: %d\n", tech);

   buf = (uint8_t *)e->GetByteArrayElements(data, NULL);
   buflen = (uint32_t)e->GetArrayLength(data);
 
   /* Prepare transceive info structure */
   if(tech == TARGET_TYPE_MIFARE_CLASSIC || tech == TARGET_TYPE_MIFARE_UL)
   {
      offset = 2;
      transceive_info.cmd.MfCmd = (phNfc_eMifareCmdList_t)buf[0];
      transceive_info.addr = (uint8_t)buf[1];
   }
   else if(tech == TARGET_TYPE_ISO14443_4)
   {
      transceive_info.cmd.Iso144434Cmd = phNfc_eIso14443_4_Raw;
      transceive_info.addr = 0;
   }
      
   transceive_info.sSendData.buffer = buf + offset;
   transceive_info.sSendData.length = buflen - offset;
   transceive_info.sRecvData.buffer = (uint8_t*)malloc(1024);
   transceive_info.sRecvData.length = 1024;

   if(transceive_info.sRecvData.buffer == NULL)
   {
      goto clean_and_return;
   }

   TRACE("phLibNfc_RemoteDev_Transceive(SMX)");
   REENTRANCE_LOCK();
   status = phLibNfc_RemoteDev_Transceive(handle, &transceive_info,
		   com_android_nfc_jni_transceive_callback, (void *)&cb_data);
   REENTRANCE_UNLOCK();
   if(status != NFCSTATUS_PENDING)
   {
      LOGE("phLibNfc_RemoteDev_Transceive(SMX) returned 0x%04x[%s]", status, nfc_jni_get_status_name(status));
      goto clean_and_return;
   }
   TRACE("phLibNfc_RemoteDev_Transceive(SMX) returned 0x%04x[%s]", status, nfc_jni_get_status_name(status));

   /* Wait for callback response */
   if(sem_wait(&cb_data.sem))
   {
       LOGE("TRANSCEIVE semaphore error");
       goto clean_and_return;
   }

   if(cb_data.status != NFCSTATUS_SUCCESS)
   {
      LOGE("TRANSCEIVE error");
      goto clean_and_return;
   }

   /* Copy results back to Java */
   result = e->NewByteArray(com_android_nfc_jni_transceive_buffer->length);
   if(result != NULL)
   {
      e->SetByteArrayRegion(result, 0,
    		  com_android_nfc_jni_transceive_buffer->length,
         (jbyte *)com_android_nfc_jni_transceive_buffer->buffer);
   }

clean_and_return:
   if(transceive_info.sRecvData.buffer != NULL)
   {
      free(transceive_info.sRecvData.buffer);
   }

   e->ReleaseByteArrayElements(data,
      (jbyte *)transceive_info.sSendData.buffer, JNI_ABORT);

   CONCURRENCY_UNLOCK();

   return result;
}
开发者ID:qingyue,项目名称:platform_packages,代码行数:99,代码来源:com_android_nfc_NativeNfcSecureElement.cpp


示例18: wait_main

static void wait_main()
{
	do {
	    sem_wait(&thread_sem);
	} while(0);
}
开发者ID:tricky1997,项目名称:tcpseg-detector,代码行数:6,代码来源:detector.c


示例19: rping_test_server

static int rping_test_server(struct rping_cb *cb)
{
	struct ibv_send_wr *bad_wr;
	int ret;

	while (1) {
		/* Wait for client's Start STAG/TO/Len */
		sem_wait(&cb->sem);
		if (cb->state != RDMA_READ_ADV) {
			fprintf(stderr, "wait for RDMA_READ_ADV state %d\n",
				cb->state);
			ret = -1;
			break;
		}

		DEBUG_LOG("server received sink adv\n");

		/* Issue RDMA Read. */
		cb->rdma_sq_wr.opcode = IBV_WR_RDMA_READ;
		cb->rdma_sq_wr.wr.rdma.rkey = cb->remote_rkey;
		cb->rdma_sq_wr.wr.rdma.remote_addr = cb->remote_addr;
		cb->rdma_sq_wr.sg_list->length = cb->remote_len;

		ret = ibv_post_send(cb->qp, &cb->rdma_sq_wr, &bad_wr);
		if (ret) {
			fprintf(stderr, "post send error %d\n", ret);
			break;
		}
		DEBUG_LOG("server posted rdma read req \n");

		/* Wait for read completion */
		sem_wait(&cb->sem);
		if (cb->state != RDMA_READ_COMPLETE) {
			fprintf(stderr, "wait for RDMA_READ_COMPLETE state %d\n",
				cb->state);
			ret = -1;
			break;
		}
		DEBUG_LOG("server received read complete\n");

		/* Display data in recv buf */
		if (cb->verbose)
			printf("server ping data: %s\n", cb->rdma_buf);

		/* Tell client to continue */
		ret = ibv_post_send(cb->qp, &cb->sq_wr, &bad_wr);
		if (ret) {
			fprintf(stderr, "post send error %d\n", ret);
			break;
		}
		DEBUG_LOG("server posted go ahead\n");

		/* Wait for client's RDMA STAG/TO/Len */
		sem_wait(&cb->sem);
		if (cb->state != RDMA_WRITE_ADV) {
			fprintf(stderr, "wait for RDMA_WRITE_ADV state %d\n",
				cb->state);
			ret = -1;
			break;
		}
		DEBUG_LOG("server received sink adv\n");

		/* RDMA Write echo data */
		cb->rdma_sq_wr.opcode = IBV_WR_RDMA_WRITE;
		cb->rdma_sq_wr.wr.rdma.rkey = cb->remote_rkey;
		cb->rdma_sq_wr.wr.rdma.remote_addr = cb->remote_addr;
		cb->rdma_sq_wr.sg_list->length = strlen(cb->rdma_buf) + 1;
		DEBUG_LOG("rdma write from lkey %x laddr %" PRIx64 " len %d\n",
			  cb->rdma_sq_wr.sg_list->lkey,
			  cb->rdma_sq_wr.sg_list->addr,
			  cb->rdma_sq_wr.sg_list->length);

		ret = ibv_post_send(cb->qp, &cb->rdma_sq_wr, &bad_wr);
		if (ret) {
			fprintf(stderr, "post send error %d\n", ret);
			break;
		}

		/* Wait for completion */
		ret = sem_wait(&cb->sem);
		if (cb->state != RDMA_WRITE_COMPLETE) {
			fprintf(stderr, "wait for RDMA_WRITE_COMPLETE state %d\n",
				cb->state);
			ret = -1;
			break;
		}
		DEBUG_LOG("server rdma write complete \n");

		/* Tell client to begin again */
		ret = ibv_post_send(cb->qp, &cb->sq_wr, &bad_wr);
		if (ret) {
			fprintf(stderr, "post send error %d\n", ret);
			break;
		}
		DEBUG_LOG("server posted go ahead\n");
	}

	return ret;
}
开发者ID:2014-class,项目名称:freerouter,代码行数:99,代码来源:rping.c


示例20: wait_thread

static void wait_thread()
{
	do {
	    sem_wait(&main_sem);
	} while(0);
}
开发者ID:tricky1997,项目名称:tcpseg-detector,代码行数:6,代码来源:detector.c



注:本文中的sem_wait函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ sema_init函数代码示例发布时间:2022-05-30
下一篇:
C++ sem_v函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap