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

C++ sem_init函数代码示例

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

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



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

示例1: pthread_create


//.........这里部分代码省略.........
        ptcb->cmn.flags    |= TCB_FLAG_SCHED_FIFO;
        break;

#if CONFIG_RR_INTERVAL > 0
      case SCHED_RR:
        ptcb->cmn.flags    |= TCB_FLAG_SCHED_RR;
        ptcb->cmn.timeslice = MSEC2TICK(CONFIG_RR_INTERVAL);
        break;
#endif

#ifdef CONFIG_SCHED_SPORADIC
      case SCHED_SPORADIC:
        ptcb->cmn.flags    |= TCB_FLAG_SCHED_SPORADIC;
        break;
#endif

#if 0 /* Not supported */
      case SCHED_OTHER:
        ptcb->cmn.flags    |= TCB_FLAG_SCHED_OTHER;
        break;
#endif
    }

  /* Get the assigned pid before we start the task (who knows what
   * could happen to ptcb after this!).  Copy this ID into the join structure
   * as well.
   */

  pid = (int)ptcb->cmn.pid;
  pjoin->thread = (pthread_t)pid;

  /* Initialize the semaphores in the join structure to zero. */

  ret = sem_init(&pjoin->data_sem, 0, 0);
  if (ret == OK)
    {
      ret = sem_init(&pjoin->exit_sem, 0, 0);
    }

  /* Activate the task */

  sched_lock();
  if (ret == OK)
    {
      ret = task_activate((FAR struct tcb_s *)ptcb);
    }

  if (ret == OK)
    {
      /* Wait for the task to actually get running and to register
       * its join structure.
       */

      (void)pthread_takesemaphore(&pjoin->data_sem);

      /* Return the thread information to the caller */

      if (thread)
       {
         *thread = (pthread_t)pid;
       }

      if (!pjoin->started)
        {
          ret = EINVAL;
        }
开发者ID:justdoitding,项目名称:Nuttx_PSoC4,代码行数:67,代码来源:pthread_create.c


示例2: main

/* main: this is supposedly required for a C program
 * 1. Create threads to handle clients
 * 2. Add clients from the file
 * 3. Join threads and leave
 * Returns 0 if everything was done correctly.
 */
int main(int argc, char** argv)
{	
	int num_queries, num_threads;
	long i;
	pthread_t * tids;

	if(argc != 3)
	{	
		fprintf(stderr,
			"USAGE: %s [input_file_path] [num_threads]\n",
			argv[0]);
		exit(1);
	}	

	// do preliminary work (database, queue, etc.)
	setup_queue();
	populate_database("TwitterDB.txt");

	num_threads = atoi(argv[2]);

	sem_init(&queue_access, 0, 1);
	sem_init(&empty, 0, 0);
	sem_init(&served, 0, 1);
	sem_init(&full, 0, num_threads);


	// create threads to handle clients
	tids = calloc(num_threads, sizeof(pthread_t));
	for(i = 0; i < num_threads; i++)
	{
	 	if(pthread_create(&tids[i], NULL, serveClients, (void *)(i + 1)))
		{
			perror("main: could not create create thread");
		    exit(1);
		}
	}	

	// populate queue
	num_queries = buildQueue(argv[1]);

	while(num_served != num_queries);
	

   	// cancel threads
	for (i = 0; i < num_threads; i++) 
	{
		if(pthread_cancel(tids[i])) 
		{
			perror("main: could not join thread");
		    exit(1);
		}
	}

	// clean up
	destroy_database();
	destroy_queue();

	free(tids);

	printf("Finished handling all clients\n");
	return 0;
}
开发者ID:uofuonye,项目名称:TwitterTrend,代码行数:68,代码来源:main.c


示例3: main

int
main(int argc, char **argv, char **envp)
{
	int	i;

	scale_init(argc, argv);

#define ALIGNMENTOFFSET 2 /* adjust alignment */
        i = sizeof(workStruct_t)*
            (narrays+ALIGNMENTOFFSET);
        element = memalign(64, i);
	if ( element == NULL ) {
	    perror("calloc( narrays, sizeof(workStruct_t) )");
	    exit(1);
	}
        compute_set(element);
        memset(element, 0, i);
        element+=ALIGNMENTOFFSET;

#ifdef SELFTEST
	start_prof();
#endif

	fid = open_output("mttest.acct");
	if (job_index == -1) {
		i = (sizeof(scripttab)/sizeof( struct scripttab) -1 );
	} else {
		i = 1;
	}
	fprintf(fid, "Number of tests: %d  Repeat count: %d\n",
		i, repeat_count);

	fprintf(fid, "MHz: %d\n", get_clock_rate() );

	fprintf(fid,
	    "X    Incl. Total   Incl. CPU   Incl. Sync. Wait   Name (%s)\n",
		model);
	fflush(fid);
  
	name = strdup(argv[0]);

	init_micro_acct();
#if OS(Solaris) 
	if(uniprocessor != 0) {
	    /* call processor_bind to force single CPU */
	    processor_bind(P_PID, P_MYID, cpuid, NULL);
	}
#endif /* OS(Solaris) */

#ifdef SOLARIS
	sema_init(&global_sema_lock, count, USYNC_THREAD, NULL);
#endif
#ifdef POSIX
	pthread_attr_init(&attr);

    #ifdef BOUND
	pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
    #endif

	sem_init(&global_sema_lock, 0, count);
#endif

#if 0
	if ((s5_sema_id = semget(IPC_PRIVATE, 1, 0600)) == -1)
		perror("semget: IPC_PRIVATE");

	arg.val = count;
	if (semctl(s5_sema_id, 0, SETVAL, arg) == -1)
		perror("semctl: SETVAL");
#endif

	resolve_symbols();

	i = locktest();
#if 0
	if (semctl(s5_sema_id, 0, IPC_RMID) == -1)
		perror("semctl: IPC_RMID");
#endif

	close_file(fid);

#ifdef SELFTEST
        finish_prof();
#endif

	return 0;
}
开发者ID:dhaley,项目名称:dcp,代码行数:87,代码来源:mttest.c


示例4: main

int main(int argc, char**argv)
{
  // Set up our exception signal handler for asserts and segfaults.
  signal(SIGABRT, signal_handler);
  signal(SIGSEGV, signal_handler);

  sem_init(&term_sem, 0, 0);
  signal(SIGTERM, terminate_handler);

  AstaireResolver* astaire_resolver = NULL;

  struct options options;
  options.local_host = "127.0.0.1";
  options.http_address = "0.0.0.0";
  options.http_port = 11888;
  options.http_threads = 1;
  options.http_worker_threads = 50;
  options.homestead_http_name = "homestead-http-name.unknown";
  options.digest_timeout = 300;
  options.home_domain = "home.domain";
  options.sas_system_name = "";
  options.access_log_enabled = false;
  options.log_to_file = false;
  options.log_level = 0;
  options.astaire = "";
  options.cassandra = "";
  options.memcached_write_format = MemcachedWriteFormat::JSON;
  options.target_latency_us = 100000;
  options.max_tokens = 1000;
  options.init_token_rate = 100.0;
  options.min_token_rate = 10.0;
  options.min_token_rate = 0.0;
  options.exception_max_ttl = 600;
  options.astaire_blacklist_duration = AstaireResolver::DEFAULT_BLACKLIST_DURATION;
  options.http_blacklist_duration = HttpResolver::DEFAULT_BLACKLIST_DURATION;
  options.pidfile = "";
  options.daemon = false;

  if (init_logging_options(argc, argv, options) != 0)
  {
    return 1;
  }

  Utils::daemon_log_setup(argc,
                          argv,
                          options.daemon,
                          options.log_directory,
                          options.log_level,
                          options.log_to_file);

  std::stringstream options_ss;

  for (int ii = 0; ii < argc; ii++)
  {
    options_ss << argv[ii];
    options_ss << " ";
  }

  std::string options_str = "Command-line options were: " + options_ss.str();

  TRC_INFO(options_str.c_str());

  if (init_options(argc, argv, options) != 0)
  {
    return 1;
  }

  if (options.pidfile != "")
  {
    int rc = Utils::lock_and_write_pidfile(options.pidfile);
    if (rc == -1)
    {
      // Failure to acquire pidfile lock
      TRC_ERROR("Could not write pidfile - exiting");
      return 2;
    }
  }

  start_signal_handlers();

  AccessLogger* access_logger = NULL;

  if (options.access_log_enabled)
  {
    TRC_STATUS("Access logging enabled to %s", options.access_log_directory.c_str());
    access_logger = new AccessLogger(options.access_log_directory);
  }

  HealthChecker* hc = new HealthChecker();
  hc->start_thread();

  // Create an exception handler. The exception handler doesn't need
  // to quiesce the process before killing it.
  exception_handler = new ExceptionHandler(options.exception_max_ttl,
                                           false,
                                           hc);

  // Initialise the SasService, to read the SAS config to pass into SAS::Init
  SasService* sas_service = new SasService(options.sas_system_name, "memento", false);

//.........这里部分代码省略.........
开发者ID:Metaswitch,项目名称:memento,代码行数:101,代码来源:main.cpp


示例5: main

int main() {

    // 初始化线程同步变量
    sem_init(&sem,0,0);

    // 从环境变量中读取登录信息
    char * CTP_FrontAddress = getenv("CTP_FrontAddress");
    if ( CTP_FrontAddress == NULL ) {
        printf("环境变量CTP_FrontAddress没有设置\n");
        return(0);
    }

    char * CTP_BrokerId = getenv("CTP_BrokerId");
    if ( CTP_BrokerId == NULL ) {
        printf("环境变量CTP_BrokerId没有设置\n");
        return(0);
    }
    strcpy(userLoginField.BrokerID,CTP_BrokerId);

    char * CTP_UserId = getenv("CTP_UserId");
    if ( CTP_UserId == NULL ) {
        printf("环境变量CTP_UserId没有设置\n");
        return(0);
    }
    strcpy(userLoginField.UserID,CTP_UserId);

    char * CTP_Password = getenv("CTP_Password");
    if ( CTP_Password == NULL ) {
        printf("环境变量CTP_Password没有设置\n");
        return(0);
    }
    strcpy(userLoginField.Password,CTP_Password);

    // 创建TraderAPI和回调响应控制器的实例
    CThostFtdcTraderApi *pTraderApi = CThostFtdcTraderApi::CreateFtdcTraderApi();
    CTraderHandler traderHandler = CTraderHandler();
    CTraderHandler * pTraderHandler = &traderHandler;
    pTraderApi->RegisterSpi(pTraderHandler);

    // 设置服务器地址
    pTraderApi->RegisterFront(CTP_FrontAddress);
    // 链接交易系统
    pTraderApi->Init();
    // 等待服务器发出登录消息
    sem_wait(&sem);
    // 发出登陆请求
    pTraderApi->ReqUserLogin(&userLoginField, requestID++);
    // 等待登录成功消息
    sem_wait(&sem);

    ////////////////////////////////////////////////////////////////////////////////////////////////
    ///请求查询资金账户
    ///////////////////////////////////////////////////////////////////////////////////////////////
    // 定义调用API的数据结构
    CThostFtdcQryTradingAccountField requestData;
    // 确保没有初始化的数据不会被访问
    memset(&requestData,0,sizeof(requestData));
    // 为调用结构题设置参数信息
    ///经纪公司代码 TThostFtdcBrokerIDType char[11]
    strcpy(requestData.BrokerID,"");
    ///投资者代码 TThostFtdcInvestorIDType char[13]
    strcpy(requestData.InvestorID,"");
    ///币种代码 TThostFtdcCurrencyIDType char[4]
    strcpy(requestData.CurrencyID,"");


    // 调用API,并等待响应函数返回
    int result = pTraderApi->ReqQryTradingAccount(&requestData,requestID++);
    sem_wait(&sem);

    /////////////////////////////////////////////////////////////////////////////////////////////////


    // 拷贝用户登录信息到登出信息
    strcpy(userLogoutField.BrokerID,userLoginField.BrokerID);
    strcpy(userLogoutField.UserID, userLoginField.UserID);
    pTraderApi->ReqUserLogout(&userLogoutField, requestID++);

    // 等待登出成功
    sem_wait(&sem);

    printf("主线程执行完毕!\n");
    return(0);

}
开发者ID:sunyongjie1984,项目名称:ctp_examples,代码行数:85,代码来源:QryTradingAccount.cpp


示例6: add_list

//添加一个新的连接目标
static int add_list(st_sock* sts, s_link* pslink)
{
	int res = EX_UDP_ERROR;
	int id = 0;
	st_idList* idList = NULL;

	if (list_empty(&sts->listIDAllocationHead))
	{
		LOG_WRITE_POS(LOG_ERR, "ERROR: More than the maximum number of links !\r\n");
		free(pslink);
		return EX_UDP_ERROR;
	}
	idList = (st_idList*)list_begin(&sts->listIDAllocationHead);
	id = idList->id;
	list_erase(&idList->list);

	//初始从第一个序号开始读和发送
	pslink->SeqRead = 1;
	pslink->SeqMaxSend = 1;
	pslink->SeqCheckSend = 0;
	pslink->timeoutCheckLack.tv_sec = 0;
	pslink->timeoutCheckLack.tv_usec = CHECK_INTERVAL_INIT;
	pslink->paArrayRecv[0].head.seq = 1;
	pslink->paArraySend[0].head.seq = 1;
	pslink->timeout_times = 1;
	pslink->timeout.tv_sec = 0;
	pslink->tsWaitTime = sts->tsWaitTime;
	gettimeofday(&pslink->timeoutSend, NULL);
	//pslink->timeoutReportLack = pslink->timeoutSend;
	pslink->linkState = 0;

	printf_debug2("&pslink=%x, pslink=%x, pslink->SeqRead=%d\n", &pslink, pslink, pslink->SeqRead);
	
	//初始化互斥量,使用默认的互斥量属性
	res = sem_init(&pslink->semRecvList, 0, 1);
	if(res != 0)  
	{
		LOG_WRITE_POS(LOG_ERR, "sem_init failed\n");
		exit(EXIT_FAILURE);  
	}

	res = sem_init(&pslink->semSendList, 0, 1);
	if(res != 0)  
	{  
		LOG_WRITE_POS(LOG_ERR, "sem_init failed\n");  
		exit(EXIT_FAILURE);  
	}

	res = sem_init(&pslink->semRecvListMutex, 0, 1);
	if(res != 0)  
	{
		LOG_WRITE_POS(LOG_ERR, "sem_init failed\n");
		exit(EXIT_FAILURE);  
	}

	res = sem_init(&pslink->semSendListMutex, 0, 1);
	if(res != 0)  
	{  
		LOG_WRITE_POS(LOG_ERR, "sem_init failed\n");  
		exit(EXIT_FAILURE);  
	}

	pslink->id = id;
	sts->pLinkIDArray[id] = pslink;
	list_push_back(&sts->list, &pslink->list);
	LOG_WRITE_POS(LOG_NOTICE, "Add connection id. id=%d, ip=%s, port=%d, sock=%d\r\n", pslink->id, inet_ntoa(*(struct in_addr*)&pslink->ip), pslink->port, pslink->socket);
	sem_post(&sts->semAccept);
	sem_post(&sts->semListen);
	printf_debug2("add_list id=%d\r\n", pslink->id);
	return EX_UDP_OK;
}
开发者ID:alvis-yuan,项目名称:utils-modules,代码行数:72,代码来源:ex_udp.c


示例7: priority_inheritance

void priority_inheritance(void)
{
#if defined(CONFIG_PRIORITY_INHERITANCE) && !defined(CONFIG_DISABLE_SIGNALS) && !defined(CONFIG_DISABLE_PTHREAD)
	pthread_t lowpri[NLOWPRI_THREADS];
	pthread_t medpri;
	pthread_t highpri[NHIGHPRI_THREADS];
	pthread_addr_t result;
	pthread_attr_t attr;
	struct sched_param sparam;
	int my_pri;
	int status;
	int i;

	printf("priority_inheritance: Started\n");

	g_middlestate = NOTSTARTED;
	for (i = 0; i < NHIGHPRI_THREADS; i++) {
		g_highstate[i] = NOTSTARTED;
	}
	for (i = 0; i < NLOWPRI_THREADS; i++) {
		g_lowstate[i]  = NOTSTARTED;
	}

	status = sched_getparam(getpid(), &sparam);
	if (status != 0) {
		printf("priority_inheritance: sched_getparam failed\n");
		sparam.sched_priority = PTHREAD_DEFAULT_PRIORITY;
	}
	my_pri  = sparam.sched_priority;

	g_highpri = sched_get_priority_max(SCHED_FIFO);
	g_lowpri = sched_get_priority_min(SCHED_FIFO);
	g_medpri = my_pri - 1;

	sem_init(&g_sem, 0, NLOWPRI_THREADS);
	dump_nfreeholders("priority_inheritance:");

	/* Start the low priority threads */

	for (i = 0; i < NLOWPRI_THREADS; i++) {
		int threadno = i + 1;
		printf("priority_inheritance: Starting lowpri_thread-%d (of %d) at %d\n",
			   threadno, NLOWPRI_THREADS, g_lowpri);
		status = pthread_attr_init(&attr);
		if (status != 0) {
			printf("priority_inheritance: pthread_attr_init failed, status=%d\n", status);
		}
		sparam.sched_priority = g_lowpri;
		status = pthread_attr_setschedparam(&attr, & sparam);
		if (status != OK) {
			printf("priority_inheritance: pthread_attr_setschedparam failed, status=%d\n", status);
		} else {
			printf("priority_inheritance: Set lowpri_thread-%d priority to %d\n",
				   threadno, sparam.sched_priority);
		}

		status = pthread_create(&lowpri[i], &attr, lowpri_thread, (void *)threadno);
		if (status != 0) {
			printf("priority_inheritance: pthread_create failed, status=%d\n", status);
		}
	}
	printf("priority_inheritance: Waiting...\n");
	sleep(2);
	dump_nfreeholders("priority_inheritance:");

	/* Start the medium priority thread */

	printf("priority_inheritance: Starting medpri_thread at %d\n", g_medpri);
	status = pthread_attr_init(&attr);
	if (status != 0) {
		printf("priority_inheritance: pthread_attr_init failed, status=%d\n", status);
	}

	sparam.sched_priority = g_medpri;
	status = pthread_attr_setschedparam(&attr, & sparam);
	if (status != OK) {
		printf("priority_inheritance: pthread_attr_setschedparam failed, status=%d\n", status);
	} else {
		printf("priority_inheritance: Set medpri_thread priority to %d\n", sparam.sched_priority);
	}
	FFLUSH();

	status = pthread_create(&medpri, &attr, medpri_thread, NULL);
	if (status != 0) {
		printf("priority_inheritance: pthread_create failed, status=%d\n", status);
	}
	printf("priority_inheritance: Waiting...\n");
	sleep(1);
	dump_nfreeholders("priority_inheritance:");

	/* Start the high priority threads */

	for (i = 0; i < NHIGHPRI_THREADS; i++) {
		int threadno = i + 1;
		printf("priority_inheritance: Starting highpri_thread-%d (of %d) at %d\n",
			   threadno, NHIGHPRI_THREADS, g_highpri);
		status = pthread_attr_init(&attr);
		if (status != 0) {
			printf("priority_inheritance: pthread_attr_init failed, status=%d\n", status);
		}
//.........这里部分代码省略.........
开发者ID:drashti304,项目名称:TizenRT,代码行数:101,代码来源:prioinherit.c


示例8: sem_init

Semaphore::Semaphore(int initial = 0) {
	sem_init(&sem,0,initial);
}
开发者ID:nikolabebic95,项目名称:Fakultet,代码行数:3,代码来源:Semaphore.cpp


示例9: main


//.........这里部分代码省略.........
        /* If we got a good PID, then we can exit the parent process. */
        if (child_pid > 0) {
            exit (EXIT_SUCCESS);    /* Success */
        }

        /* Change file mode mask */
        umask (0);

        /* Create a new SID for the child process */
        child_sid = setsid ();
        if (child_sid < 0) {
            exit (EXIT_FAILURE);     /* Failure */
        }

        /* Change the current working directory */
        if ((chdir("/")) < 0) {
            exit (EXIT_FAILURE);     /* Failure */
        }
    }

    /* Setup the signal handlers */
    if (signal (SIGINT, signal_handler) == SIG_ERR) {
        Osal_printf ("SIGINT registration failed!");
    }
    if (signal (SIGTERM, signal_handler) == SIG_ERR) {
        Osal_printf ("SIGTERM registration failed!");
    }

    while (restart) {
        restart = FALSE;
        isSysM3Event = FALSE;
        isAppM3Event = FALSE;

        sem_init (&semDaemonWait, 0, 0);

        status = ipcSetup (images [0], images [1]);
        if (status < 0) {
            Osal_printf ("ipcSetup failed!\n");
            sem_destroy (&semDaemonWait);
            return (-1);
        }
        Osal_printf ("ipcSetup succeeded!\n");

        /* Create the SysM3 fault handler thread */
        Osal_printf ("Create SysM3 event handler thread\n");
        status = pthread_create (&sysM3EvtHandlerThrd, NULL,
                                    (Void *)&sysM3EventHandler, NULL);

        if (status) {
            Osal_printf ("Error Creating SysM3 event handler thread:%d\n",
                            status);
            ipcCleanup ();
            sem_destroy (&semDaemonWait);
            exit (EXIT_FAILURE);
        }
        /* Only if AppM3 image is specified */
        if (images [1]) {
            /* Create an AppM3 fault handler thread */
            Osal_printf ("Create AppM3 event handler thread\n");
            status = pthread_create (&appM3EvtHandlerThrd, NULL,
                                        (Void *)&appM3EventHandler, NULL);
            if (status) {
                Osal_printf ("Error Creating AppM3 event handler thread:%d\n",
                                status);
                pthread_kill (sysM3EvtHandlerThrd, SIGTERM);
                sysM3EvtHandlerThrd = 0;
开发者ID:ioz9,项目名称:lewa_code_hardware,代码行数:67,代码来源:SyslinkDaemon.c


示例10: main

/***** main program *****/
int main(int argc, char *argv[])
{
	pthread_mutex_t mtx_null, mtx_def;
	pthread_mutexattr_t mattr;
	pthread_t thr;
	
	pthread_mutex_t * tab_mutex[2]={&mtx_null, &mtx_def};
	int tab_res[2][3]={{0,0,0},{0,0,0}};
	
	int ret;
	void * th_ret;
	
	int i;
	
	output_init();
	
	#if VERBOSE >1
	output("Test starting...\n");
	#endif
	
	/* We first initialize the two mutexes. */
	if ((ret=pthread_mutex_init(&mtx_null, NULL)))
	{ UNRESOLVED(ret, "NULL mutex init"); }
	
	if ((ret=pthread_mutexattr_init(&mattr)))
	{ UNRESOLVED(ret, "Mutex attribute init"); }
	if ((ret=pthread_mutex_init(&mtx_def, &mattr)))
	{ UNRESOLVED(ret, "Default attribute mutex init"); }
	
	if ((ret=pthread_mutexattr_destroy(&mattr)))
	{ UNRESOLVED(ret, "Mutex attribute destroy"); }

	
	if ((ret=sem_init(&semA, 0, 0)))
	{ UNRESOLVED(errno, "Sem A init"); }
	if ((ret=sem_init(&semB, 0, 0)))
	{ UNRESOLVED(errno, "Sem B init"); }

	#if VERBOSE >1
	output("Data initialized...\n");
	#endif
	
	
	/* OK let's go for the first part of the test : abnormals unlocking */
	
	/* We first check if unlocking an unlocked mutex returns an error. */
	retval = pthread_mutex_unlock(tab_mutex[0]);
	ret = pthread_mutex_unlock(tab_mutex[1]);
	#if VERBOSE >0
	output("Results for unlock issue #1:\n mutex 1 unlocking returned %i\n mutex 2 unlocking returned %i\n",
				retval, ret);
	#endif
	if (ret != retval)
	{
		FAILED("Unlocking an unlocked mutex behaves differently.");
	}
	
    /* Now we focus on unlocking a mutex lock by another thread */
	for (i=0; i<2; i++)
	{
		p_mtx = tab_mutex[i];
		tab_res[i][0]=0;
		tab_res[i][1]=0;
		tab_res[i][2]=0;
				
		#if VERBOSE >1
		output("Creating thread (unlock)...\n");
		#endif

		if ((ret = pthread_create(&thr, NULL, unlock_issue, NULL)))
		{ UNRESOLVED(ret, "Unlock issue thread create"); }
		
		if ((ret = sem_wait(&semA)))
		{ UNRESOLVED(errno, "Sem A wait failed for unlock issue."); }
	
		#if VERBOSE >1
		output("Unlocking in parent...\n");
		#endif
		retval = pthread_mutex_unlock(p_mtx);
		
		if ((ret = sem_post(&semB)))
		{ UNRESOLVED(errno, "Sem B post failed for unlock issue."); }
		
		if ((ret=pthread_join(thr, &th_ret)))
		{ UNRESOLVED(ret, "Join thread"); }

		#if VERBOSE >1
		output("Thread joined successfully...\n");
		#endif
		
		tab_res[i][0] = retval;
	}
	#if VERBOSE >0
	output("Results for unlock issue #2:\n mutex 1 returned %i\n mutex 2 returned %i\n",
				tab_res[0][0],tab_res[1][0]);
	#endif
	
	if (tab_res[0][0] != tab_res[1][0])
	{
//.........这里部分代码省略.........
开发者ID:SummerSnail2014,项目名称:haiku,代码行数:101,代码来源:1-2.c


示例11: standby_list_init

int standby_list_init(standby_list *s, int size) {
    s->head = NULL;
    s->tail = NULL;
    s->avail_size = size;
    return sem_init(&s->lock, 1);
}
开发者ID:HelloBinge,项目名称:EECS-343,代码行数:6,代码来源:seats.c


示例12: Sem_init

void Sem_init(sem_t *sem, int pshared, unsigned int value) 
{
    if (sem_init(sem, pshared, value) < 0)
	unix_error("Sem_init error");
}
开发者ID:bitchbitch,项目名称:ACM-ICPC,代码行数:5,代码来源:echoclient.c


示例13: pthread_mutexattr_init

//sem_getvalue on a semaphore waited on n times
TInt CTestSemgetvalue::TestSem318( )
	{
	
	int retval = 0;
	int errsum=0, err = 0;
	ThreadData lThreadData;
	
	sem_t lSignalSemaphore;
	sem_t lSuspendSemaphore;

	sem_t           lTestSemaphore;
	pthread_mutex_t lTestMutex;
	pthread_cond_t  lTestCondVar;
	pthread_condattr_t  lCondAttr;
	pthread_mutexattr_t lTestMutexAttr;

	pthread_mutexattr_t defaultattr;
	pthread_mutexattr_t errorcheckattr;
	pthread_mutexattr_t recursiveattr;

	pthread_mutexattr_init(&defaultattr);
	pthread_mutexattr_init(&errorcheckattr);
	pthread_mutexattr_init(&recursiveattr);

	pthread_mutexattr_settype(&errorcheckattr,PTHREAD_MUTEX_ERRORCHECK);
	pthread_mutexattr_settype(&recursiveattr,PTHREAD_MUTEX_RECURSIVE);


	pthread_mutex_t l_staticmutex = PTHREAD_MUTEX_INITIALIZER;
	pthread_mutex_t l_errorcheckmutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
	pthread_mutex_t l_recursivemutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
    pthread_cond_t  l_staticcondvar = PTHREAD_COND_INITIALIZER;

    CommonData lCommonData;
    lCommonData.iStaticMutex = &l_staticmutex;
	lCommonData.iErrorCheckMutex = &l_errorcheckmutex;
	lCommonData.iRecursiveMutex = &l_recursivemutex;
	lCommonData.iStaticCondVar = &l_staticcondvar;

	retval = sem_init(&lSignalSemaphore,0,0);
	if(retval != 0)
		{
		return retval;
		}

	retval = sem_init(&lSuspendSemaphore,0,0);
	if(retval != 0)
		{
		return retval;
		}

	lThreadData.iSignalSemaphore = &lSignalSemaphore;
	lThreadData.iSuspendSemaphore = &lSuspendSemaphore;
	lThreadData.iTestSemaphore   = &lTestSemaphore;
	lThreadData.iTestMutex       = &lTestMutex;
	lThreadData.iTestMutexAttr   = &lTestMutexAttr;
	lThreadData.iTestCondVar     = &lTestCondVar;
	lThreadData.iDefaultAttr     = &defaultattr;
	lThreadData.iErrorcheckAttr = &errorcheckattr;
	lThreadData.iRecursiveAttr   = &recursiveattr;

	lThreadData.iCondAttr        = &lCondAttr;
	for (int loop = 0; loop < EThreadMain; loop++)
		{
	    g_spinFlag[loop] = true;
		}
	lThreadData.iSuspending      = false;
	lThreadData.iSpinCounter     = 0;
	lThreadData.iCurrentCommand  = -1;
	lThreadData.iSelf            = EThreadMain;
	lThreadData.iValue           = 0;
	lThreadData.iRetValue        = 0;
	lThreadData.ierrno           = 0;
	lThreadData.iExpectederrno   = 0;
	lThreadData.iTimes           = 0;
	lThreadData.iStopped         = false;
	lThreadData.iCommonData      = &lCommonData;
	
	
	retval = SemInit(&lThreadData);
	
	fp=func1;
	retval = ThreadCreate(&lThreadData, (void*) EThread1);
	
	fp=func2;
	retval = ThreadCreate(&lThreadData, (void*) EThread2);
	
	fp=func3;
	retval = ThreadCreate(&lThreadData, (void*) EThread3);
	
	fp=func4;
	retval = ThreadCreate(&lThreadData, (void*) EThread4);
	
	WaitTillSuspended(&lThreadData, (void*) EThread1);
	WaitTillSuspended(&lThreadData, (void*) EThread2);
	WaitTillSuspended(&lThreadData, (void*) EThread3);
	WaitTillSuspended(&lThreadData, (void*) EThread4);
	retval = SemGetValue(&lThreadData);
	retval = CheckValue(&lThreadData,-4);
//.........这里部分代码省略.........
开发者ID:cdaffara,项目名称:symbiandump-os2,代码行数:101,代码来源:tsemgetvaluecases.cpp


示例14: pthread_mutex_lock

/****************************** INITIALIZATION *******************************/
int SCP_concurrent::init( bool bcount = false )
{
	/* lock global mutex */
	int result = pthread_mutex_lock( &mrh_mutex );
	int ret, ret_init;
	switch (result)
	{
	case 0:		// OK
		/* initialize binary semaphore with 0 */
		ret_init = sem_init( &(mr_event_table[ mn_id ]), 0, 0 );
		if(bcount)
		{
			/* iterator for count table */
			std::map<int, int>::iterator it;
			/* pick first element in the map */
			it = mr_count_table.begin();
			/* check if its count is valid number */
			if( (*it).second >= 0 )
			{
				/* runtime; init count variable with count
				 * variable of any other object (let it
				 * be first) */
				mr_count_table[ mn_id ] = (*it).second;
			}
			else
			{
				/* assign 0 in case of bad element */
				mr_count_table[ mn_id ] = 0;
			}
		}
		else
		{
			/* startup; init count variable with 0 */
			mr_count_table[ mn_id ] = 0;
		}
		/* init missedwakeups variable with 0 */
		mr_missed_wakeups[ mn_id ] = 0;
		/* release global mutex */
		ret = pthread_mutex_unlock( &mrh_mutex );
		switch(ret)
		{
		case 0:		/* success */
			/* if not zero,return semaphore initialization error */
			if( ret_init != 0 )
				return -3;
			else
				break;
		case EINVAL:
			/* mutex has not been properly initialized */
			return -2;
		default:
			/* other mutex problem */
			return -1;
		}

		break;
	case EINVAL:
		/* mutex has not been properly initialized */
		return -2;
	case EDEADLK:
		/* mutex is already owned by the calling thread */
		return -4;
	default:
		/* other mutex problem */
		return -1;
	}
	return 1;	/* return SUCCESS */
}
开发者ID:voldymyr,项目名称:SCP,代码行数:69,代码来源:scp_impl.cpp


示例15: main

Int main (Int argc, Char * argv [])
{
    pthread_t           thread_sys; /* server thread object */
    pthread_t           thread_app; /* server thread object */
    pthread_t           thread_dsp; /* server thread object */
    Char              * log_file    = NULL;
    Bool                daemon      = TRUE;
    Int                 i;
    traceBufferParams   args_sys;
    traceBufferParams   args_app;
    traceBufferParams   args_dsp;

    /* parse cmd-line args */
    for (i = 1; i < argc; i++) {
        if (!strcmp ("-l", argv[i])) {
            if (++i >= argc) {
                printUsageExit (argv[0]);
            }
            log_file = argv[i];
        }
        else if (!strcmp ("-f", argv[i])) {
            daemon = FALSE;
        }
        else if (!strcmp ("-h", argv[i])) {
            printUsageExit (argv[0]);
        }
    }

    Osal_printf ("Spawning Ducati-Tesla Trace daemon...\n");

    if (daemon) {
        pid_t child_pid;
        pid_t child_sid;

        /* Fork off the parent process */
        child_pid = fork ();
        if (child_pid < 0) {
            Osal_printf ("Spawning Trace daemon failed!\n");
            exit (EXIT_FAILURE);     /* Failure */
        }

        /* If we got a good PID, then we can exit the parent process. */
        if (child_pid > 0) {
            exit (EXIT_SUCCESS);    /* Success */
        }

        /* Create a new SID for the child process */
        child_sid = setsid ();
        if (child_sid < 0) {
            Osal_printf ("setsid failed!\n");
            exit (EXIT_FAILURE);     /* Failure */
        }
    }

    if (log_file == NULL) {
        log = NULL;
    }
    else {
        if (strcmp (log_file, "stdout") == 0) {
            /* why do we need this?  It would be an issue when logging to file.. */
            /* Change file mode mask */
            umask (0);
            log = stdout;
        }
        else {
            log = fopen (log_file, "a+");
            if (log == NULL ) {
                Osal_printf("Failed to open file: %s\n", log_file);
                exit (EXIT_FAILURE);     /* Failure */
            }
        }
    }

    /* Change the current working directory */
    if ((chdir("/")) < 0) {
        Osal_printf ("chdir failed!\n");
        exit (EXIT_FAILURE);     /* Failure */
    }

    sem_init (&semPrint, 0, 1);

    UsrUtilsDrv_setup ();

    args_sys.coreName = "[SYSM3]: ";
    args_sys.bufferAddress = SYSM3_TRACE_BUFFER_PHYS_ADDR;
    args_app.coreName = "[APPM3]: ";
    args_app.bufferAddress = APPM3_TRACE_BUFFER_PHYS_ADDR;
    args_dsp.coreName = "[DSP]: ";
    args_dsp.bufferAddress = TESLA_TRACE_BUFFER_PHYS_ADDR;

    pthread_create (&thread_sys, NULL, (Void *)&printRemoteTraces,
                    (Void*)&args_sys);
    pthread_create (&thread_app, NULL, (Void *)&printRemoteTraces,
                    (Void*)&args_app);
    pthread_create (&thread_dsp, NULL, (Void *)&printRemoteTraces,
                    (Void*)&args_dsp);

    pthread_join (thread_sys, NULL);
    Osal_printf ("SysM3 trace thread exited\n");
    pthread_join (thread_app, NULL);
//.........这里部分代码省略.........
开发者ID:ioz9,项目名称:lewa_code_hardware,代码行数:101,代码来源:SyslinkTraceDaemon.c


示例16: main

int main(void){

	int ret = -1;
	pthread_t thread_uartRec;
	int on = 1;



	//Initialize socket
	if((sockfd = socket(AF_INET, SOCK_STREAM,0))==-1){
		perror("socket");
		exit(1);
	};

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(SERV_PORT);

	if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0){
		perror("sockopt error");
		exit(1);
	}

	if(bind(sockfd, (struct sockaddr *)&servaddr,sizeof(servaddr)) == -1){
		perror("bind error");
		exit(1);
	}
	if(listen(sockfd,10)<0){  
		perror("listen");  
		exit(1);  
	}
	//Initialize UART2
	if((uartfd=open_port(uartfd,4)) < 0)//打开串口 3
	{
		perror("open_port error1\n");
		exit(1);
	}
	if((ret=set_opt(uartfd,9600,8,'N',1)) < 0)//设置串口 9600 8 N 1
	{
		perror("set_opt error1\n");
		exit(1);
	}
	/*Initialize list*/
	clientListHead = initList();

	/*Intialize semaphore*/
	ret = sem_init(&uart_sem, 0, 1);
	if(ret == -1){
		perror("semaphore create fail!");
		exit(EXIT_FAILURE);
	}
	ret = pthread_create (&thread_uartRec, NULL, (void*)(&pthread_UART2WiFi), NULL);
	if (ret != 0)
	{
	 perror ("pthread_create error!");
	}




	while(1){
		pthread_t thread_id = 0;
		size_t len = sizeof(struct sockaddr);

		clifd = accept(sockfd, (struct sockaddr *)&cliaddr, &len);
		if(clifd < 0){
			perror("error accept\n");
		}

		appendList(clifd);
		/*Create Thread to send CMD from uart to wifi*/
		ret = pthread_create (&thread_id, NULL, (void*)(&pthread_wifiUart), (void*)(&clifd));
		if (ret != 0)
		{
		 perror ("pthread_create error!");
		}
	}



	ret = shutdown(sockfd,SHUT_WR);
	assert(ret != -1);
	return 0;
}
开发者ID:Sanfork,项目名称:NanopiProject,代码行数:85,代码来源:Matrix-wifiuart.c


示例17: group_allocate

int group_allocate(FAR struct task_tcb_s *tcb, uint8_t ttype)
{
  FAR struct task_group_s *group;
  int ret;

  DEBUGASSERT(tcb && !tcb->cmn.group);

  /* Allocate the group structure and assign it to the TCB */

  group = (FAR struct task_group_s *)kmm_zalloc(sizeof(struct task_group_s));
  if (!group)
    {
      return -ENOMEM;
    }

#if CONFIG_NFILE_STREAMS > 0 && (defined(CONFIG_BUILD_PROTECTED) || \
    defined(CONFIG_BUILD_KERNEL)) && defined(CONFIG_MM_KERNEL_HEAP)
  /* If this group is being created for a privileged thread, then all elements
   * of the group must be created for privileged access.
   */

  if ((ttype & TCB_FLAG_TTYPE_MASK) == TCB_FLAG_TTYPE_KERNEL)
    {
      group->tg_flags |= GROUP_FLAG_PRIVILEGED;
    }

  /* In a flat, single-heap build.  The stream list is allocated with the
   * group structure.  But in a kernel build with a kernel allocator, it
   * must be separately allocated using a user-space allocator.
   */

  group->tg_streamlist = (FAR struct streamlist *)
    group_zalloc(group, sizeof(struct streamlist));

  if (!group->tg_streamlist)
    {
      kmm_free(group);
      return -ENOMEM;
    }

#endif

  /* Attach the group to the TCB */

  tcb->cmn.group = group;

#if defined(HAVE_GROUP_MEMBERS) || defined(CONFIG_ARCH_ADDRENV)
  /* Assign the group a unique ID.  If g_gidcounter were to wrap before we
   * finish with task creation, that would be a problem.
   */

  group_assigngid(group);
#endif

  /* Duplicate the parent tasks environment */

  ret = env_dup(group);
  if (ret < 0)
    {
#if CONFIG_NFILE_STREAMS > 0 && (defined(CONFIG_BUILD_PROTECTED) || \
    defined(CONFIG_BUILD_KERNEL)) && defined(CONFIG_MM_KERNEL_HEAP)
      group_free(group, group->tg_streamlist);
#endif
      kmm_free(group);
      tcb->cmn.group = NULL;
      return ret;
    }

#ifndef CONFIG_DISABLE_PTHREAD
  /* Initialize the pthread join semaphore */

  (void)sem_init(&group->tg_joinsem, 0, 1);
#endif

#if defined(CONFIG_SCHED_WAITPID) && !defined(CONFIG_SCHED_HAVE_PARENT)
  /* Initialize the exit/wait semaphores
   *
   * This semaphore is used for signaling and, hence, should not have
   * priority inheritance enabled.
   */

  (void)sem_init(&group->tg_exitsem, 0, 0);
  (void)sem_setprotocol(&group->tg_exitsem, SEM_PRIO_NONE);
#endif

  return OK;
}
开发者ID:a1ien,项目名称:nuttx,代码行数:87,代码来源:group_create.c


示例18: PcieTestBenchIndication

 PcieTestBenchIndication(unsigned int id) : PcieTestBenchIndicationWrapper(id), cnt(0)
 {
   sem_init(&sem, 0, 0);
 }
开发者ID:chamdoo,项目名称:xbsv,代码行数:4,代码来源:testpcie.cpp


示例19: main

/** parent thread function **/
int main(int argc, char * argv[])
{
	int ret;
	int i;
	pthread_mutexattr_t ma;
	pthread_t  child;

	output_init();

	#if VERBOSE >1
	output("Initialize the PTHREAD_MUTEX_RECURSIVE mutex\n");
	#endif

	/* Initialize the semaphore */
	if ((ret = sem_init(&sem, 0, 0)))
	{  UNRESOLVED(ret, "Sem init failed");  }

	/* We initialize the recursive mutex */
	if ((ret = pthread_mutexattr_init(&ma)))
	{  UNRESOLVED(ret, "Mutex attribute init failed");  }

	if ((ret = pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_RECURSIVE)))
	{  UNRESOLVED(ret, "Set type RECURSIVE failed");  }

	if ((ret = pthread_mutex_init(&mtx, &ma)))
	{  UNRESOLVED(ret, "Recursive mutex init failed");  }

	if ((ret = pthread_mutexattr_destroy(&ma)))
	{  UNRESOLVED(ret, "Mutex attribute destroy failed");  }

	/* -- The mutex is now ready for testing -- */

	/* First, we lock it twice and unlock once */
	if ((ret = pthread_mutex_lock(&mtx)))
	{ UNRESOLVED(ret, "First lock failed");  }

	if ((ret = pthread_mutex_lock(&mtx)))
	{ FAILED("Second lock failed");  }

	if ((ret = pthread_mutex_unlock(&mtx)))
	{ FAILED("First unlock failed");  }

	#if VERBOSE >1
	output("The mutex has been locked twice and unlocked once, start the thread now.\n");
	#endif

	/* Here this thread owns the mutex and the internal count is "1" */

	/* We create the child thread */
	if ((ret = pthread_create(&child, NULL, threaded, NULL)))
	{  UNRESOLVED(ret, "Unable to create child thread");  }

	/* then wait for child to be ready */
	if ((ret = sem_wait(&sem)))
	{  UNRESOLVED(errno, "Wait sem in child failed");  }

	#if VERBOSE >1
	output("[main] unlock the mutex.\n");
	#endif

	/* We can now unlock the mutex */
	if ((ret = pthread_mutex_unlock(&mtx)))
	{ FAILED("Second unlock failed");  }

	/* We wait for the child to lock the mutex */
	if ((ret = sem_wait(&sem)))
	{  UNRESOLVED(errno, "Wait sem in child failed");  }

	/* Then, try to unlock the mutex (owned by the child or unlocked) */
	ret = pthread_mutex_unlock(&mtx);
	if (ret == 0)
	{ FAILED("Unlock of unowned mutex succeeds");  }

	/* Everything seems OK here */
	if ((ret = pthread_join(child, NULL)))
	{  UNRESOLVED(ret, "Child join failed");  }

	/* Simple loop to double-check */
	#if VERBOSE >1
	output("[main] joined the thread.\n");
	output("Lock & unlock the mutex 50 times.\n");
	#endif

	for (i=0; i<50; i++)
	{
		if ((ret = pthread_mutex_lock(&mtx)))
		{  FAILED("Lock failed in loop");  }
	}
	for (i=0; i<50; i++)
	{
		if ((ret = pthread_mutex_unlock(&mtx)))
		{  FAILED("Unlock failed in loop");  }
	}

	ret = pthread_mutex_unlock(&mtx);
	if (ret == 0)
	{  FAILED("Unlock succeeds after the loop");  }

	#if VERBOSE >1
//.........这里部分代码省略.........
开发者ID:shubmit,项目名称:shub-ltp,代码行数:101,代码来源:4-1.c


示例20: dim_init

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ sem_open函数代码示例发布时间:2022-05-30
下一篇:
C++ sem_ids函数代码示例发布时间: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