int pthread_create(FAR pthread_t *thread, FAR const pthread_attr_t *attr, pthread_startroutine_t start_routine, pthread_addr_t arg) { FAR struct pthread_tcb_s *ptcb; FAR struct join_s *pjoin; struct sched_param param; int policy; int errcode; pid_t pid; int ret; #ifdef HAVE_TASK_GROUP bool group_joined = false; #endif /* If attributes were not supplied, use the default attributes */ if (!attr) { attr = &g_default_pthread_attr; } /* Allocate a TCB for the new task. */ ptcb = (FAR struct pthread_tcb_s *)kmm_zalloc(sizeof(struct pthread_tcb_s)); if (!ptcb) { sdbg("ERROR: Failed to allocate TCB\n"); return ENOMEM; } #ifdef HAVE_TASK_GROUP /* Bind the parent's group to the new TCB (we have not yet joined the * group). */ ret = group_bind(ptcb); if (ret < 0) { errcode = ENOMEM; goto errout_with_tcb; } #endif #ifdef CONFIG_ARCH_ADDRENV /* Share the address environment of the parent task group. */ ret = up_addrenv_attach(ptcb->cmn.group, (FAR struct tcb_s *)g_readytorun.head); if (ret < 0) { errcode = -ret; goto errout_with_tcb; } #endif /* Allocate a detachable structure to support pthread_join logic */ pjoin = (FAR struct join_s *)kmm_zalloc(sizeof(struct join_s)); if (!pjoin) { sdbg("ERROR: Failed to allocate join\n"); errcode = ENOMEM; goto errout_with_tcb; } /* Allocate the stack for the TCB */ ret = up_create_stack((FAR struct tcb_s *)ptcb, attr->stacksize, TCB_FLAG_TTYPE_PTHREAD); if (ret != OK) { errcode = ENOMEM; goto errout_with_join; } /* Should we use the priority and scheduler specified in the pthread * attributes? Or should we use the current thread's priority and * scheduler? */ if (attr->inheritsched == PTHREAD_INHERIT_SCHED) { /* Get the priority (and any other scheduling parameters) for this * thread. */ ret = sched_getparam(0, ¶m); if (ret == ERROR) { errcode = get_errno(); goto errout_with_join; } /* Get the scheduler policy for this thread */ policy = sched_getscheduler(0); if (policy == ERROR) { errcode = get_errno(); goto errout_with_join; } } else { /* Use the scheduler policy and policy the attributes */ policy = attr->policy; param.sched_priority = attr->priority; #ifdef CONFIG_SCHED_SPORADIC param.sched_ss_low_priority = attr->low_priority; param.sched_ss_max_repl = attr->max_repl; param.sched_ss_repl_period.tv_sec = attr->repl_period.tv_sec; param.sched_ss_repl_period.tv_nsec = attr->repl_period.tv_nsec; param.sched_ss_init_budget.tv_sec = attr->budget.tv_sec; param.sched_ss_init_budget.tv_nsec = attr->budget.tv_nsec; #endif } #ifdef CONFIG_SCHED_SPORADIC if (policy == SCHED_SPORADIC) { FAR struct sporadic_s *sporadic; int repl_ticks; int budget_ticks; /* Convert timespec values to system clock ticks */ (void)clock_time2ticks(¶m.sched_ss_repl_period, &repl_ticks); (void)clock_time2ticks(¶m.sched_ss_init_budget, &budget_ticks); /* The replenishment period must be greater than or equal to the * budget period. */ if (repl_ticks < budget_ticks) { errcode = EINVAL; goto errout_with_join; } /* Initialize the sporadic policy */ ret = sched_sporadic_initialize(&ptcb->cmn); if (ret >= 0) { sporadic = ptcb->cmn.sporadic; DEBUGASSERT(sporadic != NULL); /* Save the sporadic scheduling parameters */ sporadic->hi_priority = param.sched_priority; sporadic->low_priority = param.sched_ss_low_priority; sporadic->max_repl = param.sched_ss_max_repl; sporadic->repl_period = repl_ticks; sporadic->budget = budget_ticks; /* And start the first replenishment interval */ ret = sched_sporadic_start(&ptcb->cmn); } /* Handle any failures */ if (ret < 0) { errcode = -ret; goto errout_with_join; } } #endif /* Initialize the task control block */ ret = pthread_schedsetup(ptcb, param.sched_priority, pthread_start, start_routine); if (ret != OK) { errcode = EBUSY; goto errout_with_join; } /* Configure the TCB for a pthread receiving on parameter * passed by value */ pthread_argsetup(ptcb, arg); #ifdef HAVE_TASK_GROUP /* Join the parent's task group */ ret = group_join(ptcb); if (ret < 0) { errcode = ENOMEM; goto errout_with_join; } group_joined = true; #endif /* Attach the join info to the TCB. */ ptcb->joininfo = (FAR void *)pjoin; /* Set the appropriate scheduling policy in the TCB */ ptcb->cmn.flags &= ~TCB_FLAG_POLICY_MASK; switch (policy) { default: DEBUGPANIC(); case SCHED_FIFO: 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; } sched_unlock(); (void)sem_destroy(&pjoin->data_sem); } else { sched_unlock(); dq_rem((FAR dq_entry_t *)ptcb, (FAR dq_queue_t *)&g_inactivetasks); (void)sem_destroy(&pjoin->data_sem); (void)sem_destroy(&pjoin->exit_sem); errcode = EIO; goto errout_with_join; } return ret; errout_with_join: sched_kfree(pjoin); ptcb->joininfo = NULL; errout_with_tcb: #ifdef HAVE_TASK_GROUP /* Clear group binding */ if (ptcb && !group_joined) { ptcb->cmn.group = NULL; } #endif sched_releasetcb((FAR struct tcb_s *)ptcb, TCB_FLAG_TTYPE_PTHREAD); return errcode; }
/* 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; }
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; }
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); // Ensure our random numbers are unpredictable. unsigned int seed; seed = time(NULL) ^ getpid(); srand(seed); // Create a DNS resolver. int af = AF_INET; struct in6_addr dummy_addr; if (inet_pton(AF_INET6, options.local_host.c_str(), &dummy_addr) == 1) { TRC_DEBUG("Local host is an IPv6 address"); af = AF_INET6; } DnsCachedResolver* dns_resolver = new DnsCachedResolver("127.0.0.1"); // Create alarm and communication monitor objects for the conditions // reported by memento. AlarmManager* alarm_manager = new AlarmManager(); CommunicationMonitor* astaire_comm_monitor = new CommunicationMonitor(new Alarm(alarm_manager, "memento", AlarmDef::MEMENTO_ASTAIRE_COMM_ERROR, AlarmDef::CRITICAL), "Memento", "Astaire"); CommunicationMonitor* hs_comm_monitor = new CommunicationMonitor(new Alarm(alarm_manager, "memento", AlarmDef::MEMENTO_HOMESTEAD_COMM_ERROR, AlarmDef::CRITICAL), "Memento", "Homestead"); CommunicationMonitor* cass_comm_monitor = new CommunicationMonitor(new Alarm(alarm_manager, "memento", AlarmDef::MEMENTO_CASSANDRA_COMM_ERROR, AlarmDef::CRITICAL), "Memento", "Cassandra"); astaire_resolver = new AstaireResolver(dns_resolver, af, options.astaire_blacklist_duration); // Default the astaire hostname to the loopback IP if (options.astaire == "") { if (af == AF_INET6) { options.astaire = "[::1]"; } else { options.astaire = "127.0.0.1"; } } memcached_store = (Store*)new TopologyNeutralMemcachedStore(options.astaire, astaire_resolver, false, astaire_comm_monitor); AuthStore::SerializerDeserializer* serializer; std::vector<AuthStore::SerializerDeserializer*> deserializers; if (options.memcached_write_format == MemcachedWriteFormat::JSON) { serializer = new AuthStore::JsonSerializerDeserializer(); } else { serializer = new AuthStore::BinarySerializerDeserializer(); } deserializers.push_back(new AuthStore::JsonSerializerDeserializer()); deserializers.push_back(new AuthStore::BinarySerializerDeserializer()); AuthStore* auth_store = new AuthStore(memcached_store, serializer, deserializers, options.digest_timeout); LoadMonitor* load_monitor = new LoadMonitor(options.target_latency_us, options.max_tokens, options.init_token_rate, options.min_token_rate, options.max_token_rate); LastValueCache* stats_aggregator = new MementoLVC(); // Create a HTTP specific resolver. HttpResolver* http_resolver = new HttpResolver(dns_resolver, af, options.http_blacklist_duration); HttpClient* http_client = new HttpClient(false, http_resolver, nullptr, load_monitor, SASEvent::HttpLogLevel::PROTOCOL, hs_comm_monitor); HttpConnection* http_connection = new HttpConnection(options.homestead_http_name, http_client); HomesteadConnection* homestead_conn = new HomesteadConnection(http_connection); // Default to a 30s blacklist/graylist duration and port 9160 CassandraResolver* cass_resolver = new CassandraResolver(dns_resolver, af, 30, 30, 9160); // Default the cassandra hostname to the loopback IP if (options.cassandra == "") { if (af == AF_INET6) { options.cassandra = "[::1]"; } else { options.cassandra = "127.0.0.1"; } } // Create and start the call list store. CallListStore::Store* call_list_store = new CallListStore::Store(); call_list_store->configure_connection(options.cassandra, 9160, cass_comm_monitor, cass_resolver); // Test Cassandra connectivity. CassandraStore::ResultCode store_rc = call_list_store->connection_test(); if (store_rc == CassandraStore::OK) { // Store can connect to Cassandra, so start it. store_rc = call_list_store->start(); } if (store_rc != CassandraStore::OK) { TRC_ERROR("Unable to create call list store (RC = %d)", store_rc); exit(3); } HttpStackUtils::SimpleStatsManager stats_manager(stats_aggregator); HttpStack* http_stack = new HttpStack(options.http_threads, exception_handler, access_logger, load_monitor, &stats_manager); CallListTask::Config call_list_config(auth_store, homestead_conn, call_list_store, options.home_domain, stats_aggregator, hc, options.api_key); MementoSasLogger sas_logger; HttpStackUtils::PingHandler ping_handler; HttpStackUtils::SpawningHandler<CallListTask, CallListTask::Config> call_list_handler(&call_list_config, &sas_logger); HttpStackUtils::HandlerThreadPool pool(options.http_worker_threads, exception_handler); try { http_stack->initialize(); http_stack->bind_tcp_socket(options.http_address, options.http_port); http_stack->register_handler("^/ping$", &ping_handler); http_stack->register_handler("^/org.projectclearwater.call-list/users/[^/]*/call-list.xml$", pool.wrap(&call_list_handler)); http_stack->start(); } catch (HttpStack::Exception& e) { TRC_ERROR("Failed to initialize HttpStack stack - function %s, rc %d", e._func, e._rc); exit(2); } TRC_STATUS("Start-up complete - wait for termination signal"); sem_wait(&term_sem); TRC_STATUS("Termination signal received - terminating"); try { http_stack->stop(); http_stack->wait_stopped(); } catch (HttpStack::Exception& e) { TRC_ERROR("Failed to stop HttpStack stack - function %s, rc %d", e._func, e._rc); } call_list_store->stop(); call_list_store->wait_stopped(); hc->stop_thread(); delete homestead_conn; homestead_conn = NULL; delete http_connection; http_connection = NULL; delete http_client; http_client = NULL; delete call_list_store; call_list_store = NULL; delete http_resolver; http_resolver = NULL; delete cass_resolver; cass_resolver = NULL; delete dns_resolver; dns_resolver = NULL; delete load_monitor; load_monitor = NULL; delete auth_store; auth_store = NULL; delete call_list_store; call_list_store = NULL; delete astaire_resolver; astaire_resolver = NULL; delete memcached_store; memcached_store = NULL; delete exception_handler; exception_handler = NULL; delete hc; hc = NULL; delete http_stack; http_stack = NULL; delete astaire_comm_monitor; astaire_comm_monitor = NULL; delete hs_comm_monitor; hs_comm_monitor = NULL; delete cass_comm_monitor; cass_comm_monitor = NULL; delete alarm_manager; alarm_manager = NULL; delete sas_service; sas_service = NULL; signal(SIGTERM, SIG_DFL); sem_destroy(&term_sem); }
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); }
//添加一个新的连接目标 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; }
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); } sparam.sched_priority = g_highpri - i; 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 highpri_thread-%d priority to %d\n", threadno, sparam.sched_priority); } FFLUSH(); status = pthread_create(&highpri[i], &attr, highpri_thread, (void *)threadno); if (status != 0) { printf("priority_inheritance: pthread_create failed, status=%d\n", status); } } dump_nfreeholders("priority_inheritance:"); FFLUSH(); /* Wait for all thread instances to complete */ for (i = 0; i < NHIGHPRI_THREADS; i++) { printf("priority_inheritance: Waiting for highpri_thread-%d to complete\n", i + 1); FFLUSH(); (void)pthread_join(highpri[i], &result); dump_nfreeholders("priority_inheritance:"); } printf("priority_inheritance: Waiting for medpri_thread to complete\n"); FFLUSH(); (void)pthread_join(medpri, &result); dump_nfreeholders("priority_inheritance:"); for (i = 0; i < NLOWPRI_THREADS; i++) { printf("priority_inheritance: Waiting for lowpri_thread-%d to complete\n", i + 1); FFLUSH(); (void)pthread_join(lowpri[i], &result); dump_nfreeholders("priority_inheritance:"); } printf("priority_inheritance: Finished\n"); sem_destroy(&g_sem); dump_nfreeholders("priority_inheritance:"); FFLUSH(); #endif /* CONFIG_PRIORITY_INHERITANCE && !CONFIG_DISABLE_SIGNALS && !CONFIG_DISABLE_PTHREAD */ }
Semaphore::Semaphore(int initial = 0) { sem_init(&sem,0,initial); }
Int main (Int argc, Char * argv []) { pid_t child_pid; pid_t child_sid; Int status = 0; Bool daemon = TRUE; Int o; Int i; Char * images [] = {NULL, NULL}; Int numImages = sizeof (images) / sizeof (images [0]); if (isDaemonRunning (argv [0])) { Osal_printf ("Multiple instances of syslink_daemon.out are not " "supported!\n"); return (-1); } /* Determine args */ while ((o = getopt (argc, argv, ":fs:a:")) != -1) { switch (o) { case 's': images [0] = optarg; break; case 'a': images [1] = optarg; break; case 'f': daemon = FALSE; break; case ':': status = -1; Osal_printf ("Option -%c requires an operand\n", optopt); break; case '?': status = -1; Osal_printf ("Unrecognized option: -%c\n", optopt); break; } } for (i = 0; optind < argc; optind++) { while (i < numImages && images [i]) i++; if (i == numImages) { printUsage (); } images [i++] = argv [optind]; } for (i = 0; i < numImages; i++) { if (images [i] && access (images [i], R_OK)) { Osal_printf ("Error opening %s\n", images [i]); printUsage (); } } if (status || optind < argc || !images [0]) { printUsage (); } /* Process will be daemonised if daemon flag is true */ if (daemon) { Osal_printf ("Spawning SysLink Daemon...\n"); /* Fork off the parent process */ child_pid = fork (); if (child_pid < 0) { Osal_printf ("Spawn 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 */ } /* 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; ipcCleanup (); sem_destroy (&semDaemonWait); exit (EXIT_FAILURE); } } /* Wait for any event handler thread to be unblocked */ sem_wait (&semDaemonWait); /* Clean up event handler threads */ if (sysM3EvtHandlerThrd) { if (isSysM3Event) { status = pthread_join (sysM3EvtHandlerThrd, NULL); Osal_printf ("pthread_join SysM3 Thread = %d\n", status); } else { if (pthread_kill (sysM3EvtHandlerThrd, SIGTERM) == 0) { status = pthread_join (sysM3EvtHandlerThrd, NULL); Osal_printf ("pthread_kill & join SysM3 Thread = %d\n", status); } } sysM3EvtHandlerThrd = 0; } if (appM3EvtHandlerThrd) { if (isAppM3Event) { status = pthread_join (appM3EvtHandlerThrd, NULL); Osal_printf ("pthread_join AppM3 Thread = %d\n", status); } else { if (pthread_kill (appM3EvtHandlerThrd, SIGTERM) == 0) { status = pthread_join (appM3EvtHandlerThrd, NULL); Osal_printf ("pthread_kill & join AppM3 Thread = %d\n", status); } } appM3EvtHandlerThrd = 0; } /* IPC_Cleanup function */ ipcCleanup (); sem_destroy (&semDaemonWait); } return 0; }
/***** 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]) { FAILED("Unlocking an unowned mutex behaves differently."); } /* We now are going to test the deadlock issue */ /* We start with testing the NULL mutex features */ 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 (deadlk)...\n"); #endif if ((ret = pthread_create(&thr, NULL, deadlk_issue, NULL))) { UNRESOLVED(ret, "Deadlk_issue thread create"); } /* Now we are waiting the thread is ready to relock the mutex. */ if ((ret=sem_wait(&semA))) { UNRESOLVED(errno, "Sem wait"); } /* To ensure thread runs until second lock, we yield here */ sched_yield(); /* OK, now we cancel the thread */ canceled=0; #if VERBOSE >1 output("Cancel thread...\n"); #endif if (returned ==0) if ((ret=pthread_cancel(thr))) { UNRESOLVED(ret, "Cancel thread (deadlk_issue)"); } #if VERBOSE >1 output("Thread canceled...\n"); #endif if ((ret=pthread_join(thr, &th_ret))) { UNRESOLVED(ret, "Join thread"); } #if VERBOSE >1 output("Thread joined successfully...\n"); #endif tab_res[i][2] = retval; tab_res[i][1] = returned; tab_res[i][0] = canceled; } /* Now we parse the results */ #if VERBOSE >0 output("Results for deadlock issue:\n mutex 1 \t%s\t%s%i\n mutex 2 \t%s\t%s%i\n", tab_res[0][0]?"deadlock" : "no deadlock", tab_res[0][1]?"returned " : "did not return ", tab_res[0][2], tab_res[1][0]?"deadlock" : "no deadlock", tab_res[1][1]?"returned " : "did not return ", tab_res[1][2]); #endif if (tab_res[0][0] != tab_res[1][0]) { FAILED("One mutex deadlocks, not the other"); } if (tab_res[0][1] != tab_res[1][1]) { UNRESOLVED(tab_res[0][1], "Abnormal situation!"); } if ((tab_res[0][1] == 1) && (tab_res[0][2] != tab_res[1][2])) { FAILED("The locks returned different error codes."); } PASSED; }
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); }
void Sem_init(sem_t *sem, int pshared, unsigned int value) { if (sem_init(sem, pshared, value) < 0) unix_error("Sem_init error"); }
//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); retval = SemPost(&lThreadData); retval = SemPost(&lThreadData); retval = SemGetValue(&lThreadData); retval = CheckValue(&lThreadData,-2); retval = SemPost(&lThreadData); retval = SemPost(&lThreadData); retval = SemGetValue(&lThreadData); retval = ThreadDestroy(&lThreadData, (void*) EThread1); retval = ThreadDestroy(&lThreadData, (void*) EThread2); retval = ThreadDestroy(&lThreadData, (void*) EThread3); retval = ThreadDestroy(&lThreadData, (void*) EThread4); retval = SemDestroy(&lThreadData); StopThread(&lThreadData); err = pthread_cond_destroy(&l_staticcondvar); if(err != EINVAL) { errsum += err; } err = pthread_mutex_destroy(&l_recursivemutex); if(err != EINVAL) { errsum += err; } err = pthread_mutex_destroy(&l_errorcheckmutex); if(err != EINVAL) { errsum += err; } err = pthread_mutex_destroy(&l_staticmutex); if(err != EINVAL) { errsum += err; } err = pthread_mutexattr_destroy(&recursiveattr); if(err != EINVAL) { errsum += err; } err = pthread_mutexattr_destroy(&errorcheckattr); if(err != EINVAL) { errsum += err; } err = pthread_mutexattr_destroy(&defaultattr); if(err != EINVAL) { errsum += err; } err = sem_destroy(&lSignalSemaphore); if(err != EINVAL) { errsum += err; } err = sem_destroy(&lSuspendSemaphore); if(err != EINVAL) { errsum += err; } return retval+errsum; }
/****************************** 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 */ }
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); Osal_printf ("AppM3 trace thread exited\n"); pthread_join (thread_dsp, NULL); Osal_printf ("Tesla trace thread exited\n"); UsrUtilsDrv_destroy (); sem_destroy (&semPrint); if (log != NULL && log != stdout ) { fclose(log); } return 0; }
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; }
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; }
PcieTestBenchIndication(unsigned int id) : PcieTestBenchIndicationWrapper(id), cnt(0) { sem_init(&sem, 0, 0); }
/** 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 output("Everything went OK; destroy the mutex.\n"); #endif /* The test passed, we destroy the mutex */ if ((ret = pthread_mutex_destroy(&mtx))) { UNRESOLVED(ret, "Final mutex destroy failed"); } PASSED; }
void dim_init() { static int done = 0; sigset_t set1; pthread_t t_id; int ret; /* #ifdef LYNXOS */ pthread_attr_t attr; /* #endif */ if(!done) { /* int prio; */ done = 1; dna_init(); /* thr_getprio(thr_self(),&prio); thr_setprio(thr_self(),prio+3); */ INIT_thread = pthread_self(); MAIN_thread = INIT_thread; #ifndef darwin sem_init(&DIM_INIT_Sema, 0, INIT_count); sem_init(&DIM_WAIT_Sema, 0, WAIT_count); #else DIM_INIT_Semap = sem_open("/Dim_INIT_Sem", O_CREAT, S_IRUSR | S_IWUSR, INIT_count); DIM_WAIT_Semap = sem_open("/Dim_WAIT_Sem", O_CREAT, S_IRUSR | S_IWUSR, WAIT_count); #endif ignore_sigpipe(); #ifdef LYNXOS pthread_attr_create(&attr); pthread_create(&t_id, attr, dim_dtq_thread, 0); #else /* pthread_create(&t_id, NULL, dim_dtq_thread, 0); */ pthread_attr_init(&attr); pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED); pthread_create(&t_id, &attr, dim_dtq_thread, 0); #endif #ifndef darwin ret = sem_wait(&DIM_INIT_Sema); #else ret = sem_wait(DIM_INIT_Semap); #endif #ifdef LYNXOS pthread_create(&t_id, attr, dim_tcpip_thread, 0); #else pthread_create(&t_id, &attr, dim_tcpip_thread, 0); #endif #ifndef darwin ret = sem_wait(&DIM_INIT_Sema); #else ret = sem_wait(DIM_INIT_Semap); #endif INIT_thread = 0; } }
static struct tiva_adc_s *tiva_adc_struct_init(struct tiva_adc_cfg_s *cfg) { struct tiva_adc_s *adc = g_adcs[cfg->adc]; struct tiva_adc_sse_s *sse = 0; uint8_t s = 0; /* Do not re-initialize the run-time structures, there is a chance another * process is also using this ADC. */ if (adc->cfg == true) { goto tiva_adc_struct_init_ok; } else { if (adc != NULL) { adc->ena = false; adc->devno = cfg->adc; for (s = 0; s < 4; s++) { /* Only configure selected SSEs */ if (cfg->sse[s]) { sse = g_sses[SSE_IDX(cfg->adc, s)]; if (sse != NULL) { sse->adc = cfg->adc; sse->num = s; sem_init(&sse->exclsem, SEM_PROCESS_PRIVATE, 1); sse->ena = false; sse->cfg = true; } else { goto tiva_adc_struct_init_error; } } } /* Initialize the public ADC device data structure */ adc->dev = g_devs[cfg->adc]; if (adc->dev != NULL) { adc->dev->ad_ops = &g_adcops; adc->dev->ad_priv = adc; } else { goto tiva_adc_struct_init_error; } goto tiva_adc_struct_init_ok; } else { goto tiva_adc_struct_init_error; } } tiva_adc_struct_init_error: avdbg("Invalid ADC device number: expected=%d actual=%d\n", 0, cfg->adc); avdbg("ADC%d (CONFIG_TIVA_ADC%d) must be enabled in Kconfig first!", cfg->adc, cfg->adc); return NULL; tiva_adc_struct_init_ok: adc->cfg = true; return adc; }
int main(int argc, char** argv) { int rc; pid_t pid; //注册信号 (void)signal(TFTP_SIGNAL, Tftp_Sig); //初始化缓存队列 queue_init(&coapMsgQ, free); //初始化信号量,初始值为0 rc = sem_init(&msgQSem, 0, 0); if(rc == -1) { printf("init msgQSem error!\r\n"); exit(-1); } //初始化互斥量 rc = pthread_mutex_init(&msgQ_mutex, NULL); if(rc != 0) { printf("msgQ_mutex init error!\r\n"); exit(-1); } //打开数据库 Open_db("CoapMsg.db", &db); rc = zlog_init("log.conf"); if (rc) { printf("init failed\n"); return -1; } zc = zlog_get_category("my_cat"); if (!zc) { printf("get cat fail\n"); zlog_fini(); return -2; } zlog_info(zc, "Start!"); zlog_info(zc, "Uart_Init!"); //初始化串口 Uart_Init(115200); //创建串口读取数据线程 rc = pthread_create(&uartRd_Thread, NULL, Uart_ReadThread, NULL); if(0!=rc) { zlog_error(zc, "uartRd_Thread create error!"); exit(-1); } else { zlog_debug(zc, "uartRd_Thread create success!"); } //创建分发数据线程 rc = pthread_create(&transMsg_Thread, NULL, TransMsgThread, NULL); if(0!=rc) { zlog_error(zc, "TransMsgThread create error!"); exit(-1); } else { zlog_debug(zc, "TransMsgThread create success!"); } //初始化链表 list_init( &iplist, free); zlog_debug(zc, "list_init success!"); //创建tftp Server进程 pid = fork(); if(pid == 0) { printf("enter tftp server,pid = %d\r\n", getpid()); zlog_debug(zc, "enter tftp server,pid = %d", getpid()); tftpd_init(NULL); } else if(pid<0) { printf("create tftp server process error!\r\n"); zlog_error(zc, "create tftp server process error!"); } else if(pid > 0) { //记录tftp子进程的pid tftp_pid = pid; } //创建coapclient任务 CreatCoapclient(&iplist); //创建coap Server进程 pid = fork(); if(pid == 0) { printf("enter coap server,pid = %d\r\n", getpid()); zlog_debug(zc, "enter coap server,pid = %d", getpid()); CoapServ(NULL); } else if(pid<0) { printf("create coap server process error!\r\n"); zlog_error(zc, "create coap server process error!"); } else if(pid > 0) { //记录coap server子进程的pid coap_serv_pid = pid; } while(1) { sleep(1); } return 0; }
int do_test (void) { if (pthread_barrier_init (&b, NULL, N + 1) != 0) { puts ("barrier_init failed"); exit (1); } if (sem_init (&s, 0, 0) != 0) { puts ("sem_init failed"); exit (1); } struct sigaction sa; sa.sa_handler = handler; sigemptyset (&sa.sa_mask); sa.sa_flags = 0; if (sigaction (THE_SIG, &sa, NULL) != 0) { puts ("sigaction failed"); exit (1); } pthread_attr_t a; if (pthread_attr_init (&a) != 0) { puts ("attr_init failed"); exit (1); } if (pthread_attr_setstacksize (&a, 1 * 1024 * 1024) != 0) { puts ("attr_setstacksize failed"); return 1; } int i; for (i = 0; i < N; ++i) if (pthread_create (&th[i], &a, tf, cbs[i]) != 0) { puts ("pthread_create failed"); exit (1); } if (pthread_attr_destroy (&a) != 0) { puts ("attr_destroy failed"); exit (1); } pthread_barrier_wait (&b); sigset_t ss; sigemptyset (&ss); sigaddset (&ss, THE_SIG); if (pthread_sigmask (SIG_BLOCK, &ss, NULL) != 0) { puts ("pthread_sigmask failed"); exit (1); } /* Start sending signals. */ for (i = 0; i < TOTAL_SIGS; ++i) { if (kill (getpid (), THE_SIG) != 0) { puts ("kill failed"); exit (1); } if (TEMP_FAILURE_RETRY (sem_wait (&s)) != 0) { puts ("sem_wait failed"); exit (1); } ++nsigs; } pthread_barrier_wait (&b); for (i = 0; i < N; ++i) if (pthread_join (th[i], NULL) != 0) { puts ("join failed"); exit (1); } return 0; }
int main(int argc, const char **argv) { int i; int srcAlloc; int dstAlloc; unsigned int *srcBuffer = 0; unsigned int *dstBuffer = 0; FMComms1RequestProxy *device = 0; FMComms1Indication *deviceIndication = 0; BlueScopeEventPIORequestProxy *bluescope = 0; BlueScopeEventPIOIndication *bluescopeIndication = 0; fprintf(stdout, "Main::%s %s\n", __DATE__, __TIME__); if(sem_init(&cv_sem, 1, 0)){ fprintf(stdout, "failed to init cv_sem\n"); exit(1); } if(sem_init(&read_sem, 1, 0)){ fprintf(stdout, "failed to init read_sem\n"); exit(1); } if(sem_init(&write_sem, 1, 0)){ fprintf(stdout, "failed to init write_sem\n"); exit(1); } device = new FMComms1RequestProxy(IfcNames_FMComms1Request); DmaManager *dma = platformInit(); deviceIndication = new FMComms1Indication(IfcNames_FMComms1Indication); bluescope = new BlueScopeEventPIORequestProxy(IfcNames_BlueScopeEventPIORequest); bluescopeIndication = new BlueScopeEventPIOIndication(IfcNames_BlueScopeEventPIOIndication); fprintf(stdout, "Main::allocating memory...\n"); srcAlloc = portalAlloc(alloc_sz, 0); srcBuffer = (unsigned int *)portalMmap(srcAlloc, alloc_sz); if ((char *) srcBuffer == MAP_FAILED) perror("srcBuffer mmap failed"); assert ((char *) srcBuffer != MAP_FAILED); dstAlloc = portalAlloc(alloc_sz, 0); dstBuffer = (unsigned int *)portalMmap(dstAlloc, alloc_sz); if ((char *) dstBuffer == MAP_FAILED) perror("dstBuffer mmap failed"); assert ((char *) dstBuffer != MAP_FAILED); int status; status = setClockFrequency(0, 100000000, 0); /* FMComms1 refclk should be 30 MHz */ status = setClockFrequency(1, 30000000, 0); portalCacheFlush(srcAlloc, srcBuffer, alloc_sz, 1); portalCacheFlush(dstAlloc, dstBuffer, alloc_sz, 1); fprintf(stdout, "Main::flush and invalidate complete\n"); bluescope->doReset(); WHERE(); bluescope->setTriggerMask (0xFFFFFFFF); WHERE(); bluescope->getCounterValue(); WHERE(); bluescope->enableIndications(1); WHERE(); sem_wait(&cv_sem); fprintf(stdout, "Main::initial BlueScopeEventPIO counterValue: %d\n", counter_value); device->getReadStatus(); device->getWriteStatus(); sem_wait(&read_sem); sem_wait(&write_sem); fprintf(stdout, "Main::after getStateDbg\n"); unsigned int ref_srcAlloc = dma->reference(srcAlloc); fprintf(stdout, "ref_srcAlloc=%d\n", ref_srcAlloc); unsigned int ref_dstAlloc = dma->reference(dstAlloc); fprintf(stdout, "ref_dstAlloc=%d\n", ref_dstAlloc); fprintf(stdout, "Main::starting read %08x\n", numWords); device->startRead(ref_srcAlloc, numWords, readBurstLen, 1); device->startWrite(ref_dstAlloc, numWords, writeBurstLen, 1); sem_wait(&read_sem); sleep(5); device->getReadStatus(); device->getWriteStatus(); sem_wait(&read_sem); sem_wait(&write_sem); sleep(5); fprintf(stdout, "Main::stopping reads\n"); device->startRead(ref_srcAlloc, numWords, readBurstLen, 0); fprintf(stdout, "Main::stopping writes\n"); device->startWrite(ref_dstAlloc, numWords, writeBurstLen, 0); device->getReadStatus(); device->getWriteStatus(); sem_wait(&read_sem); sem_wait(&write_sem); testi2c("/dev/i2c-1", 0x58); bluescope->getCounterValue(); fprintf(stdout, "Main::getCounter\n"); sem_wait(&cv_sem); fprintf(stdout, "Main::final BlueScopeEventPIO counterValue: %d\n", counter_value); fprintf(stdout, "received %d events\n", eventcount); for (i = 0; i < eventcount; i += 1) { fprintf(stdout, "reportEvent(0x%08x, 0x%08x)\n", events[i], timestamps[i]); } exit(0); }
/* * Refine eigenvalues with respect to new rrr */ static inline int refine_eigvals(cluster_t *cl, int rf_begin, int rf_end, int tid, proc_t *procinfo, rrr_t *RRR, val_t *Wstruct, vec_t *Zstruct, tol_t *tolstruct, counter_t *num_left, workQ_t *workQ, double *work, int *iwork) { /* From inputs */ int rf_size = rf_end-rf_begin+1; int bl_begin = cl->bl_begin; int bl_end = cl->bl_end; int bl_size = bl_end - bl_begin + 1; double bl_spdiam = cl->bl_spdiam; int nthreads = procinfo->nthreads; double *restrict D = RRR->D; double *restrict L = RRR->L; double *restrict DLL = RRR->DLL; double *restrict W = Wstruct->W; double *restrict Werr = Wstruct->Werr; double *restrict Wgap = Wstruct->Wgap; int *restrict Windex = Wstruct->Windex; double *restrict Wshifted = Wstruct->Wshifted; int nz = Zstruct->nz; double pivmin = tolstruct->pivmin; double rtol1 = tolstruct->rtol1; double rtol2 = tolstruct->rtol2; /* Others */ int info, i, p, q, offset; double sigma, savegap; int MIN_REFINE_CHUNK = fmax(2,nz/(4*nthreads)); int left, own_part, others_part, num_tasks; int ts_begin, ts_end, chunk, count; task_t *task; sem_t sem; int num_iter; /* Determine if refinement should be split into tasks */ left = PMR_get_counter_value(num_left); own_part = (int) fmax( ceil( (double) left / nthreads ), MIN_REFINE_CHUNK); if (own_part < rf_size) { others_part = rf_size - own_part; num_tasks = iceil(rf_size, own_part) - 1; /* >1 */ chunk = others_part/num_tasks; /* floor */ sem_init(&sem, 0, 0); ts_begin = rf_begin; p = Windex[rf_begin]; for (i=0; i<num_tasks; i++) { ts_end = ts_begin + chunk - 1; q = p + chunk - 1; task = PMR_create_r_task(ts_begin, ts_end, D, DLL, p, q, bl_size, bl_spdiam, tid, &sem); if (ts_begin <= ts_end) PMR_insert_task_at_back(workQ->r_queue, task); else sem_post(&sem); /* case chunk=0 */ ts_begin = ts_end + 1; p = q + 1; } ts_end = rf_end; q = Windex[rf_end]; offset = Windex[ts_begin] - 1; /* Call bisection routine to refine the values */ if (ts_begin <= ts_end) { LAPACK(dlarrb) (&bl_size, D, DLL, &p, &q, &rtol1, &rtol2, &offset, &Wshifted[ts_begin], &Wgap[ts_begin], &Werr[ts_begin], work, iwork, &pivmin, &bl_spdiam, &bl_size, &info); assert( info == 0 ); } /* Empty "all" r-queue refine tasks before waiting */ num_iter = PMR_get_num_tasks(workQ->r_queue); for (i=0; i<num_iter; i++) { task = PMR_remove_task_at_front(workQ->r_queue); if (task != NULL) { if (task->flag == REFINE_TASK_FLAG) { PMR_process_r_task((refine_t *) task->data, procinfo, Wstruct, tolstruct, work, iwork); free(task); } else { PMR_insert_task_at_back(workQ->r_queue, task); } } /* if task */ } /* end for i */ /* Barrier: wait until all created tasks finished */ count = num_tasks; while (count > 0) { while (sem_wait(&sem) != 0) { }; count--; } sem_destroy(&sem); /* Edit right gap at splitting point */ ts_begin = rf_begin; for (i=0; i<num_tasks; i++) { ts_end = ts_begin + chunk - 1; Wgap[ts_end] = Wshifted[ts_end + 1] - Werr[ts_end + 1] - Wshifted[ts_end] - Werr[ts_end]; ts_begin = ts_end + 1; } } else { /* Refinement of cluster without creating tasks */ /* 'p' and 'q' are local (within block) indices of * the first/last eigenvalue of the cluster */ p = Windex[rf_begin]; q = Windex[rf_end]; offset = Windex[rf_begin] - 1; /* = p - 1 */ if (p == q) { savegap = Wgap[rf_begin]; Wgap[rf_begin] = 0.0; } /* Bisection routine to refine the values */ LAPACK(dlarrb) (&bl_size, D, DLL, &p, &q, &rtol1, &rtol2, &offset, &Wshifted[rf_begin], &Wgap[rf_begin], &Werr[rf_begin], work, iwork, &pivmin, &bl_spdiam, &bl_size, &info); assert( info == 0 ); if (p == q) { Wgap[rf_begin] = savegap; } } /* end refine with or without creating tasks */ sigma = L[bl_size-1]; /* refined eigenvalues with all shifts applied in W */ for (i=rf_begin; i<=rf_end; i++) { W[i] = Wshifted[i] + sigma; } return(0); } /* end refine_eigvals */
/* main function */ int main() { int ret; pthread_t child; struct sigaction sa; /* Initialize output */ output_init(); /* Set the signal handler */ sa.sa_flags = SA_RESTART; sa.sa_handler = handler; ret = sigemptyset(&sa.sa_mask); if (ret != 0) { UNRESOLVED(ret, "Failed to empty signal set"); } /* Install the signal handler for SIGNAL */ ret = sigaction(SIGNAL, &sa, 0); if (ret != 0) { UNRESOLVED(ret, "Failed to set signal handler"); } /* Initialize the semaphore */ ret = sem_init(&sem, 0, 0); if (ret != 0) { UNRESOLVED(ret, "Failed to init a semaphore"); } /* Create the child thread */ ret = pthread_create(&child, NULL, threaded, NULL); if (ret != 0) { UNRESOLVED(ret, "Failed to create a child thread"); } /* Let the child thread enter the wait routine... we use sched_yield as there is no certain way to test that the child is waiting for the semaphore... */ sched_yield(); sched_yield(); sched_yield(); /* Ok, now kill the child */ ret = pthread_kill(child, SIGNAL); if (ret != 0) { UNRESOLVED(ret, "Failed to kill the child thread"); } /* wait that the child receives the signal */ while (!caught) sched_yield(); /* Now let the child run and terminate */ ret = sem_post(&sem); if (ret != 0) { UNRESOLVED(errno, "Failed to post the semaphore"); } ret = pthread_join(child, NULL); if (ret != 0) { UNRESOLVED(ret, "Failed to join the thread"); } /* terminate */ ret = sem_destroy(&sem); if (ret != 0) { UNRESOLVED(ret, "Failed to destroy the semaphore"); } /* Test passed */ #if VERBOSE > 0 output("Test passed\n"); #endif PASSED; }
/* The main test function. */ int main(int argc, char * argv[]) { int ret, i; sem_t *sems; sem_t sem_last; long max; /* Initialize output */ output_init(); max = sysconf(_SC_SEM_NSEMS_MAX); if (max <= 0) { output("sysconf(_SC_SEM_NSEMS_MAX) = %ld\n", max); UNTESTED("There is no constraint on SEM_NSEMS_MAX"); } sems = (sem_t *) calloc(max, sizeof(sem_t)); if (sems == NULL) { UNRESOLVED(errno, "Failed to alloc space"); } for (i = 0; i < max; i++) { ret = sem_init(&sems[ i ], 0, 0); if (ret != 0) { output("sem_init failed to initialize the %d nth semaphore.\n", i); output("Tryed to initialize %ld.\n", max); output("Error is %d: %s\n", errno, strerror(errno)); for (; i > 0; i--) sem_destroy(&sems[i-1]); free(sems); PASSED; } } ret = sem_init(&sem_last, 0, 1); if (ret == 0) { FAILED("We were able to sem_init more than SEM_NSEMS_MAX semaphores"); } if (errno != ENOSPC) { output("Error is %d: %s\n", errno, strerror(errno)); } for (i = 0; i < max; i++) sem_destroy(&sems[i]); free(sems); /* Test passed */ #if VERBOSE > 0 output("Test passed\n"); #endif PASSED; }
int UHD_SAFE_MAIN(int argc, char *argv[]){ //Seting priority in the processor to run faster -> run with sudo if (!(uhd::set_thread_priority_safe(1,true))) { std::cout << "Problem setting thread priority" << std::endl; return 1; }; //variables to be set by po -> Set when initializing the rx program //double seconds_in_future=0.01; size_t total_num_samps; double rx_rate, freq, LOoffset; bool use_external_10MHz; double scaling_8bits; std::string filename; float gain; bool realTime; uhd::device_addr_t dev_addr; uhd::usrp::multi_usrp::sptr dev; uhd::tune_result_t tr; uhd::stream_args_t stream_args; uhd::rx_streamer::sptr rx_stream; //setup the program options-> Passing it from terminal with boost library po::options_description desc("Allowed options"); desc.add_options() ("help", "help message") ("nsamps", po::value<size_t>(&total_num_samps)->default_value(1000), "total number of samples to receive") ("rxrate", po::value<double>(&rx_rate)->default_value(100e6/4), "rate of incoming samples") ("freq", po::value<double>(&freq)->default_value(5.5e9), "rf center frequency in Hz") ("LOoffset", po::value<double>(&LOoffset)->default_value(10e6), "Offset between main LO and center frequency") ("10MHz",po::value<bool>(&use_external_10MHz)->default_value(false), "external 10MHz on 'REF CLOCK' connector (true=1=yes)") // ("PPS",po::value<bool>(&trigger_with_pps)->default_value(false), "trigger reception with 'PPS IN' connector (true=1=yes)") ("filename",po::value<std::string>(&filename)->default_value("data_from_usrp.dat"), "output filename") ("gain",po::value<float>(&gain)->default_value(30), "set the receiver gain") ("8bits_scaling",po::value<double>(&scaling_8bits)->default_value(0.0), "input scaling (invers) when 8bits is used, set to zero to get 16bits") ///////////////////////////// ("realTime",po::value<bool>(&realTime)->default_value(true), "receives in loop and compares with synch sequence") ; //Variables stored in boost objects po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); //print the help message if (vm.count("help")){ std::cout << boost::format("rx %s") % desc << std::endl; return ~0; } ///////////Set device variables to read data//////////////// dev_addr["addr0"]="192.168.10.2"; dev = uhd::usrp::multi_usrp::make(dev_addr);//Create the device //receiving format stream_args.cpu_format="sc16"; if (scaling_8bits==0.0) { stream_args.otw_format="sc16"; } else { stream_args.otw_format="sc8"; std::stringstream temp_ss; temp_ss << scaling_8bits; stream_args.args["peak"]=temp_ss.str(); }; rx_stream=dev->get_rx_stream(stream_args); //set/get the streamer values to the device uhd::clock_config_t my_clock_config; /* if (trigger_with_pps) { my_clock_config.pps_source=uhd::clock_config_t::PPS_SMA; }; */ if (use_external_10MHz) { my_clock_config.ref_source=uhd::clock_config_t::REF_SMA; }; /////////////////Create an USRP device//////////////////////// std::cout << std::endl; //uhd::device::sptr udev = dev->get_device(); dev->set_rx_rate(rx_rate); bool is_xcvr2450=false; uhd::dict<std::string, std::string> rx_info; rx_info=dev->get_usrp_rx_info(0); if (rx_info.has_key("rx_subdev_name")) { std::string str=rx_info.get("rx_subdev_name"); uint temp=str.find("XCVR2450"); if (temp<str.length()) { is_xcvr2450=true; }; }; if (is_xcvr2450) { dev->set_tx_antenna("J2"); dev->set_rx_antenna("J1"); //uhd::meta_range_t range=dev->get_tx_bandwidth_range(); if (LOoffset>=9e6) { dev->set_rx_bandwidth(3.96e+07); }; }; std::cout << "rx_rate=" << rx_rate << std::endl; std::cout << "freq=" << freq << std::endl; std::cout << "gain=" << gain << std::endl; uhd::tune_request_t trq(freq,LOoffset); //dev->set_rx_bandwidth(36e6); tr=dev->set_rx_freq(trq); dev->set_rx_gain(gain); std::cout << "tr=" << tr.actual_rf_freq << std::endl; if (use_external_10MHz) { dev->set_clock_config(my_clock_config); // PZ usleep(1e6); // Wait for the 10MHz to lock }; size_t buffer_size=1000; // Select buffer size uint nDetect=1000; dev->set_time_now(uhd::time_spec_t(0.0)); std::cout << boost::format("Setting device timestamp to 0...") << std::endl; //////////////////////////////////Read data to buff_short and do processing//////////// //Launch threads sem_init(&isReady, 0,0); std::thread storeT(storeDataX, rx_stream, dev, buffer_size, nDetect); std::thread detectionT(detection, nDetect); storeT.join(); detectionT.join(); //finished std::cout << std::endl << "Done receiving!" << std::endl << std::endl; return 0; }
void IpcYxFake_Client_Init(void) { sem_init(&(s_object_lock),0,1); ListInit(&(s_object_list), 0, 0); }
/** ============================================================================ * @func pool_notify_Create * * @desc This function allocates and initializes resources used by * this application. * * @modif None * ============================================================================ */ NORMAL_API DSP_STATUS pool_notify_Create (IN Char8 * dspExecutable, IN Char8 * strBufferSize, IN Uint8 processorId) { DSP_STATUS status = DSP_SOK ; Uint32 numArgs = NUM_ARGS ; Void * dspDataBuf = NULL ; Uint32 numBufs [NUM_BUF_SIZES] = {NUM_BUF_POOL0, } ; Uint32 size [NUM_BUF_SIZES] ; SMAPOOL_Attrs poolAttrs ; Char8 * args [NUM_ARGS] ; #ifdef DEBUG printf ("Entered pool_notify_Create ()\n") ; #endif sem_init(&sem,0,0); /* * Create and initialize the proc object. */ status = PROC_setup (NULL) ; /* * Attach the Dsp with which the transfers have to be done. */ if (DSP_SUCCEEDED (status)) { status = PROC_attach (processorId, NULL) ; if (DSP_FAILED (status)) { printf ("PROC_attach () failed. Status = [0x%x]\n", (int)status) ; } } else { printf ("PROC_setup () failed. Status = [0x%x]\n", (int)status) ; } /* * Open the pool. */ if (DSP_SUCCEEDED (status)) { size [0] = pool_notify_BufferSize ; poolAttrs.bufSizes = (Uint32 *) &size ; poolAttrs.numBuffers = (Uint32 *) &numBufs ; poolAttrs.numBufPools = NUM_BUF_SIZES ; poolAttrs.exactMatchReq = TRUE ; status = POOL_open (POOL_makePoolId(processorId, SAMPLE_POOL_ID), &poolAttrs) ; if (DSP_FAILED (status)) { printf ("POOL_open () failed. Status = [0x%x]\n", (int)status) ; } } /* * Allocate the data buffer to be used for the application. */ if (DSP_SUCCEEDED (status)) { status = POOL_alloc (POOL_makePoolId(processorId, SAMPLE_POOL_ID), (Void **) &pool_notify_DataBuf, pool_notify_BufferSize) ; /* Get the translated DSP address to be sent to the DSP. */ if (DSP_SUCCEEDED (status)) { status = POOL_translateAddr ( POOL_makePoolId(processorId, SAMPLE_POOL_ID), &dspDataBuf, AddrType_Dsp, (Void *) pool_notify_DataBuf, AddrType_Usr) ; if (DSP_FAILED (status)) { printf ("POOL_translateAddr () DataBuf failed." " Status = [0x%x]\n", (int)status) ; } } else { printf ("POOL_alloc () DataBuf failed. Status = [0x%x]\n", (int)status) ; } } /* * Register for notification that the DSP-side application setup is * complete. */ if (DSP_SUCCEEDED (status)) { status = NOTIFY_register (processorId, pool_notify_IPS_ID, pool_notify_IPS_EVENTNO, (FnNotifyCbck) pool_notify_Notify, 0/* vladms XFER_SemPtr*/) ; if (DSP_FAILED (status)) { printf ("NOTIFY_register () failed Status = [0x%x]\n", (int)status) ; } } /* * Load the executable on the DSP. */ if (DSP_SUCCEEDED (status)) { args [0] = strBufferSize ; { status = PROC_load (processorId, dspExecutable, numArgs, args) ; } if (DSP_FAILED (status)) { printf ("PROC_load () failed. Status = [0x%x]\n", (int)status) ; } } /* * Start execution on DSP. */ if (DSP_SUCCEEDED (status)) { status = PROC_start (processorId) ; if (DSP_FAILED (status)) { printf ("PROC_start () failed. Status = [0x%x]\n", (int)status) ; } } /* * Wait for the DSP-side application to indicate that it has completed its * setup. The DSP-side application sends notification of the IPS event * when it is ready to proceed with further execution of the application. */ if (DSP_SUCCEEDED (status)) { // wait for initialization sem_wait(&sem); } /* * Send notifications to the DSP with information about the address of the * control structure and data buffer to be used by the application. * */ status = NOTIFY_notify (processorId, pool_notify_IPS_ID, pool_notify_IPS_EVENTNO, (Uint32) dspDataBuf); if (DSP_FAILED (status)) { printf ("NOTIFY_notify () DataBuf failed." " Status = [0x%x]\n", (int)status) ; } status = NOTIFY_notify (processorId, pool_notify_IPS_ID, pool_notify_IPS_EVENTNO, (Uint32) pool_notify_BufferSize); if (DSP_FAILED (status)) { printf ("NOTIFY_notify () DataBuf failed." " Status = [0x%x]\n", (int)status) ; } #ifdef DEBUG printf ("Leaving pool_notify_Create ()\n") ; #endif return status ; }