static void * _server_socket_accept (void *arg) { thread_list_t _entry = (thread_list_t)arg; dconfig_data_t *config = _entry->config; int fd = _entry->fd; thread_list_t thread_list_head = NULL; int rc = 0; free (_entry); _entry = NULL; if (pipe (s_fd_accept_terminate) == -1) { common_log (LOG_FATAL, "pipe failed"); } while (rc != -1) { fd_set fdset; FD_ZERO (&fdset); FD_SET (s_fd_accept_terminate[0], &fdset); FD_SET (fd, &fdset); rc = select (FD_SETSIZE, &fdset, NULL, NULL, NULL); if (rc != -1 && rc != 0) { if (FD_ISSET (s_fd_accept_terminate[0], &fdset)) { accept_command_t cmd; if ( (rc = read ( s_fd_accept_terminate[0], &cmd, sizeof (cmd)) ) == sizeof (cmd) ) { if (cmd == ACCEPT_THREAD_STOP) { rc = -1; } else if (cmd == ACCEPT_THREAD_CLEAN) { thread_list_t entry = thread_list_head; thread_list_t prev = NULL; common_log (LOG_DEBUG, "Cleaning up closed thread"); while (entry != NULL) { if (entry->stopped) { thread_list_t temp = entry; common_log (LOG_DEBUG, "Cleaning up closed thread1"); pthread_join (entry->thread, NULL); close (entry->fd); if (prev == NULL) { thread_list_head = entry->next; } else { prev->next = entry->next; } entry = entry->next; free (temp); } else { prev = entry; entry = entry->next; } } } } } else if (FD_ISSET (fd, &fdset)) { struct sockaddr_un addr; socklen_t addrlen = sizeof (addr); int fd2; if ((rc = fd2 = accept (fd, (struct sockaddr *)&addr, &addrlen)) != -1) { thread_list_t entry = NULL; common_log (LOG_DEBUG, "Accepted new socket connection"); if ((entry = (thread_list_t)malloc (sizeof (struct thread_list_s))) == NULL) { common_log (LOG_FATAL, "malloc failed"); } memset (entry, 0, sizeof (struct thread_list_s)); entry->next = thread_list_head; entry->fd = fd2; entry->config = config; thread_list_head = entry; if ( pthread_create ( &entry->thread, NULL, _server_socket_command_handler, entry ) ) { common_log (LOG_FATAL, "pthread failed"); } } } } } common_log (LOG_DEBUG, "Cleaning up threads"); while (thread_list_head != NULL) { thread_list_t entry = thread_list_head; thread_list_head = thread_list_head->next; common_log (LOG_DEBUG, "Cleaning up thread1"); close (entry->fd); pthread_join (entry->thread, NULL); free (entry); } return NULL; }
int sync_worker_init(struct bladerf_sync *s) { int status = 0; s->worker = (struct sync_worker*) calloc(1, sizeof(*s->worker)); if (s->worker == NULL) { status = BLADERF_ERR_MEM; goto worker_init_out; } s->worker->state = SYNC_WORKER_STATE_STARTUP; s->worker->cb = s->stream_config.module == BLADERF_MODULE_RX ? rx_callback : tx_callback; status = bladerf_init_stream(&s->worker->stream, s->dev, s->worker->cb, &s->buf_mgmt.buffers, s->buf_mgmt.num_buffers, s->stream_config.format, s->stream_config.samples_per_buffer, s->stream_config.num_xfers, s); if (status != 0) { log_debug("%s worker: Failed to init stream: %s\n", MODULE_STR(s), bladerf_strerror(status)); goto worker_init_out; } status = pthread_mutex_init(&s->worker->state_lock, NULL); if (status != 0) { status = BLADERF_ERR_UNEXPECTED; goto worker_init_out; } status = pthread_cond_init(&s->worker->state_changed, NULL); if (status != 0) { status = BLADERF_ERR_UNEXPECTED; goto worker_init_out; } status = pthread_mutex_init(&s->worker->request_lock, NULL); if (status != 0) { status = BLADERF_ERR_UNEXPECTED; goto worker_init_out; } status = pthread_cond_init(&s->worker->requests_pending, NULL); if (status != 0) { status = BLADERF_ERR_UNEXPECTED; goto worker_init_out; } status = pthread_create(&s->worker->thread, NULL, sync_worker_task, s); if (status != 0) { status = BLADERF_ERR_UNEXPECTED; goto worker_init_out; } /* Wait until the worker thread has initialized and is ready to go */ status = sync_worker_wait_for_state(s->worker, SYNC_WORKER_STATE_IDLE, 1000); if (status != 0) { status = BLADERF_ERR_TIMEOUT; goto worker_init_out; } worker_init_out: if (status != 0) { free(s->worker); s->worker = NULL; } return status; }
int main(void) { pthread_t tid1, tid2, tid3, tid4; void *res; int err; err = pthread_create(&tid1, NULL, tfn1, NULL); if (err != 0) { printf("can't create thread %s\n", strerror(err)); exit(1); } err = pthread_join(tid1, &res); if (err != 0) { printf("can't join thread %s\n", strerror(err)); exit(1); } printf("lst result: %d, %d\n", ((struct a *)res)->b, ((struct a *)res)->c); err = pthread_create(&tid2, NULL, tfn2, NULL); if (err != 0) { printf("can't create thread %s\n", strerror(err)); exit(1); } err = pthread_join(tid2, &res); if (err != 0) { printf("can't join thread %s\n", strerror(err)); exit(1); } printf("2nd result: %d, %d\n", ((struct a *)res)->b, ((struct a *)res)->c); free(res); err = pthread_create(&tid3, NULL, tfn3, NULL); if (err != 0) { printf("can't create thread %s\n", strerror(err)); exit(1); } err = pthread_join(tid3, &res); if (err != 0) { printf("can't join thread %s\n", strerror(err)); exit(1); } printf("3rd result: %d, %d\n", ((struct a *)res)->b, ((struct a *)res)->c); struct a *p; p = (struct a *)malloc(sizeof(struct a)); p->b = 10; p->c = 11; err = pthread_create(&tid4, NULL, tfn4, (void *)p); if (err != 0) { printf("can't create thread %s\n", strerror(err)); exit(1); } err = pthread_join(tid4, &res); if (err != 0) { printf("can't join thread %s\n", strerror(err)); exit(1); } printf("4th result: %d, %d\n", ((struct a *)res)->b, ((struct a *)res)->c); free(p); return 0; }
void *phy_layer_server(void *num){ cout<<"Physical Active(PHY)"<<endl; //Setup Socket int sockfd, portno; socklen_t clilen; void *newsockfd; struct sockaddr_in serv_addr, cli_addr; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) diewithError("ERROR opening socket"); bzero((char *) &serv_addr, sizeof(serv_addr)); portno = PORT; //Basic Socket Parameters serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(portno); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) diewithError("ERROR on binding"); listen(sockfd, 5); clilen = sizeof(cli_addr); //Threads int *socket[10]; pthread_t phy_layer_thread[10]; int client=0; int rc; try{ while(1){ //Wait for clients socket[client]=(int *) malloc(sizeof(int)); cout<<"Waiting for clients (PHY)"<<endl; *socket[client]=accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); cout<<"Socket Accepted (PHY)"<<endl; // Mark the socket as non-blocking, for safety. int x; x=fcntl(*socket[client],F_GETFL,0); fcntl(*socket[client],F_SETFL,x | O_NONBLOCK); if(*socket[client]==-1) diewithError("Could not connect to client"); cout<<"Socket Made non-blocking (PHY)"<<endl; //Spawn Thread rc = pthread_create( &phy_layer_thread[client], NULL, phy_layer_t, (void*) socket[client]); if(rc)diewithError("ERROR; return code from pthread_create()"); cout<<"Thread spawned for client (PHY)"<<endl; client++; } } //Something went wrong :( catch(int e) { //Stop threads for(int i=0;i<client;i++) pthread_cancel(phy_layer_thread[i]); } return 0; }
/** * Starts AT handler on stream "fd' * returns 0 on success, -1 on error */ int at_open(int fd, ATUnsolHandler h) { int ret; pthread_t tid; pthread_attr_t attr; s_fd = fd; s_unsolHandler = h; s_readerClosed = 0; s_responsePrefix = NULL; s_smsPDU = NULL; sp_response = NULL; /* Android power control ioctl */ #ifdef HAVE_ANDROID_OS #ifdef OMAP_CSMI_POWER_CONTROL ret = ioctl(fd, OMAP_CSMI_TTY_ENABLE_ACK); if(ret == 0) { int ack_count; int read_count; int old_flags; char sync_buf[256]; old_flags = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, old_flags | O_NONBLOCK); do { ioctl(fd, OMAP_CSMI_TTY_READ_UNACKED, &ack_count); read_count = 0; do { ret = read(fd, sync_buf, sizeof(sync_buf)); if(ret > 0) read_count += ret; } while(ret > 0 || (ret < 0 && errno == EINTR)); ioctl(fd, OMAP_CSMI_TTY_ACK, &ack_count); } while(ack_count > 0 || read_count > 0); fcntl(fd, F_SETFL, old_flags); s_readCount = 0; s_ackPowerIoctl = 1; } else s_ackPowerIoctl = 0; #else // OMAP_CSMI_POWER_CONTROL s_ackPowerIoctl = 0; #endif // OMAP_CSMI_POWER_CONTROL #endif /*HAVE_ANDROID_OS*/ pthread_attr_init (&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); ret = pthread_create(&s_tid_reader, &attr, readerLoop, &attr); if (ret < 0) { perror ("pthread_create"); return -1; } return 0; }
bool OThread::Start(void *pParam, int Priority, int affinity) { if(m_bRunning) return true; m_pParam = pParam; m_bShutdown = false; int max_priority; int min_priority; int mid_priority; int min_max_diff; int min_max_diff_quarter; struct sched_param SchedVal; int iRetVal; pthread_attr_t attr; pthread_attr_init(&attr); iRetVal = pthread_attr_setschedpolicy(&attr, SCHED_OTHER); if(iRetVal != 0) return false; max_priority = sched_get_priority_max(SCHED_OTHER); min_priority = sched_get_priority_min(SCHED_OTHER); min_max_diff = max_priority - min_priority; mid_priority = (min_max_diff / 2) + min_priority; min_max_diff_quarter = min_max_diff / 4; switch(Priority) { case THREAD_PRIORITY_ABOVE_NORMAL: SchedVal.sched_priority = max_priority - min_max_diff_quarter; break; case THREAD_PRIORITY_BELOW_NORMAL: SchedVal.sched_priority = min_priority + min_max_diff_quarter; break; case THREAD_PRIORITY_HIGHEST: case THREAD_PRIORITY_TIME_CRITICAL: SchedVal.sched_priority = max_priority; break; case THREAD_PRIORITY_IDLE: SchedVal.sched_priority = min_priority; break; case THREAD_PRIORITY_NORMAL: default: SchedVal.sched_priority = mid_priority; break; } if(SchedVal.sched_priority < min_priority) SchedVal.sched_priority = min_priority; if(SchedVal.sched_priority > max_priority) SchedVal.sched_priority = max_priority; iRetVal = pthread_attr_setschedparam(&attr, &SchedVal); if(iRetVal != 0) return false; iRetVal = pthread_create(&m_thread, NULL, CThreadRunFunction, this); if(iRetVal != 0) return false; m_bRunning = true; return true; }
/*static*/ int alsa_init(cubeb ** context, char const * context_name) { cubeb * ctx; int r; int i; int fd[2]; pthread_attr_t attr; snd_pcm_t * dummy; assert(context); *context = NULL; pthread_mutex_lock(&cubeb_alsa_mutex); if (!cubeb_alsa_error_handler_set) { snd_lib_error_set_handler(silent_error_handler); cubeb_alsa_error_handler_set = 1; } pthread_mutex_unlock(&cubeb_alsa_mutex); ctx = calloc(1, sizeof(*ctx)); assert(ctx); ctx->ops = &alsa_ops; r = pthread_mutex_init(&ctx->mutex, NULL); assert(r == 0); r = pipe(fd); assert(r == 0); for (i = 0; i < 2; ++i) { fcntl(fd[i], F_SETFD, fcntl(fd[i], F_GETFD) | FD_CLOEXEC); fcntl(fd[i], F_SETFL, fcntl(fd[i], F_GETFL) | O_NONBLOCK); } ctx->control_fd_read = fd[0]; ctx->control_fd_write = fd[1]; /* Force an early rebuild when alsa_run is first called to ensure fds and nfds have been initialized. */ ctx->rebuild = 1; r = pthread_attr_init(&attr); assert(r == 0); r = pthread_attr_setstacksize(&attr, 256 * 1024); assert(r == 0); r = pthread_create(&ctx->thread, &attr, alsa_run_thread, ctx); assert(r == 0); r = pthread_attr_destroy(&attr); assert(r == 0); /* Open a dummy PCM to force the configuration space to be evaluated so that init_local_config_with_workaround can find and modify the default node. */ r = alsa_locked_pcm_open(&dummy, SND_PCM_STREAM_PLAYBACK, NULL); if (r >= 0) { alsa_locked_pcm_close(dummy); } ctx->is_pa = 0; pthread_mutex_lock(&cubeb_alsa_mutex); ctx->local_config = init_local_config_with_workaround(CUBEB_ALSA_PCM_NAME); pthread_mutex_unlock(&cubeb_alsa_mutex); if (ctx->local_config) { ctx->is_pa = 1; r = alsa_locked_pcm_open(&dummy, SND_PCM_STREAM_PLAYBACK, ctx->local_config); /* If we got a local_config, we found a PA PCM. If opening a PCM with that config fails with EINVAL, the PA PCM is too old for this workaround. */ if (r == -EINVAL) { pthread_mutex_lock(&cubeb_alsa_mutex); snd_config_delete(ctx->local_config); pthread_mutex_unlock(&cubeb_alsa_mutex); ctx->local_config = NULL; } else if (r >= 0) { alsa_locked_pcm_close(dummy); } } *context = ctx; return CUBEB_OK; }
/** * \return 1 on success, 0 if the function was interrupted and -1 on error */ int stream_enable_cache(stream_t *stream,int64_t size,int64_t min,int64_t seek_limit){ int ss = stream->sector_size ? stream->sector_size : STREAM_BUFFER_SIZE; int res = -1; cache_vars_t* s; if (stream->flags & STREAM_NON_CACHEABLE) { mp_msg(MSGT_CACHE,MSGL_STATUS,"\rThis stream is non-cacheable\n"); return 1; } if (size > SIZE_MAX) { mp_msg(MSGT_CACHE, MSGL_FATAL, "Cache size larger than max. allocation size\n"); return -1; } s=cache_init(size,ss); if(s == NULL) return -1; stream->cache_data=s; s->stream=stream; // callback s->seek_limit=seek_limit; //make sure that we won't wait from cache_fill //more data than it is allowed to fill if (s->seek_limit > s->buffer_size - s->fill_limit ){ s->seek_limit = s->buffer_size - s->fill_limit; } if (min > s->buffer_size - s->fill_limit) { min = s->buffer_size - s->fill_limit; } // to make sure we wait for the cache process/thread to be active // before continuing if (min <= 0) min = 1; #if FORKED_CACHE if((stream->cache_pid=fork())){ if ((pid_t)stream->cache_pid == -1) stream->cache_pid = 0; #else { stream_t* stream2=malloc(sizeof(stream_t)); memcpy(stream2,s->stream,sizeof(stream_t)); s->stream=stream2; #if defined(__MINGW32__) stream->cache_pid = _beginthread( ThreadProc, 0, s ); #elif defined(__OS2__) stream->cache_pid = _beginthread( ThreadProc, NULL, 256 * 1024, s ); #else { pthread_t tid; pthread_create(&tid, NULL, ThreadProc, s); stream->cache_pid = 1; } #endif #endif if (!stream->cache_pid) { mp_msg(MSGT_CACHE, MSGL_ERR, "Starting cache process/thread failed: %s.\n", strerror(errno)); goto err_out; } // wait until cache is filled at least prefill_init % mp_msg(MSGT_CACHE,MSGL_V,"CACHE_PRE_INIT: %"PRId64" [%"PRId64"] %"PRId64" pre:%"PRId64" eof:%d \n", s->min_filepos,s->read_filepos,s->max_filepos,min,s->eof); while(s->read_filepos<s->min_filepos || s->max_filepos-s->read_filepos<min){ /* mp_msg(MSGT_CACHE,MSGL_STATUS,MSGTR_CacheFill, 100.0*(float)(s->max_filepos-s->read_filepos)/(float)(s->buffer_size), s->max_filepos-s->read_filepos ); */ if(s->eof) break; // file is smaller than prefill size if(stream_check_interrupt(PREFILL_SLEEP_TIME)) { res = 0; goto err_out; } } mp_msg(MSGT_CACHE,MSGL_STATUS,"\n"); return 1; // parent exits err_out: cache_uninit(stream); return res; } #if FORKED_CACHE signal(SIGTERM,exit_sighandler); // kill cache_mainloop(s); // make sure forked code never leaves this function exit(0); #endif } #if !FORKED_CACHE #if defined(__MINGW32__) || defined(__OS2__) static void ThreadProc( void *s ){ cache_mainloop(s); _endthread(); }
void run() throw(kul::threading::Exception){ if(s) KEXCEPTION("Thread running"); f = 0; s = 1; pthread_create(&thr, NULL, Thread::threadFunction, this); }
int fvl_srio_init(fvl_srio_init_param_t *srio_param) { fvl_srio_context_t *psrio = &g_srio_context; fvl_srio_portpool_t *ppool; fvl_srio_ctrlblk_t *pscb,*cscb,*re_cscb; uint32_t chan_num=srio_param->chan_num; uint32_t buf_num=srio_param->buf_num; uint32_t buf_size=srio_param->buf_size; uint32_t chan_size=srio_param->chan_size; uint32_t ctl_size= FVL_CTL_WIN_SIZE; uint32_t port_num=srio_param->port_num; fvl_dma_pool_t *port_dma_wr = srio_param->port_rd_buf; fvl_dma_pool_t *port_dma_ctl_wp; fvl_dma_pool_t *port_dma_ctl_wr; uint32_t win_size=chan_size*chan_num; uint32_t ctl_win_size=0x1000;//ctl_size*chan_num; uint32_t win_law=0,ctl_law=0; struct srio_dev *sriodev; int rvl; if((port_num >= FVL_SRIO_PORT_NUM) || (port_num <0)) { FVL_LOG("port number error:%d\n",port_num); return -1; } if((chan_num > FVL_PORT_CHAN_NUM_MAX) || ( chan_num<0)) { FVL_LOG("channel number error:%d\n",chan_num); return -1; } if(!init_flag) { of_init(); rvl = fsl_srio_uio_init(&sriodev); if (rvl < 0) { FVL_LOG("%s(): fsl_srio_uio_init return %d\n", __func__, rvl); return rvl; } psrio->sriodev=sriodev; init_flag=1; } else { sriodev=psrio->sriodev; } //mode slave head_port[port_num].re_flag=1; head_port[port_num].uflag=0; int i=0; int j=FVL_PORT_CHAN_NUM_MAX*port_num; FVL_LOG("Slave: chan_num %d\n",chan_num); for(i=0;i<chan_num;i++) { head_channel[j+i].re_flag=1; head_channel[j+i].uflag=0; } psrio->chan_num[port_num]=chan_num; struct srio_port_info *pinfo; void *range; pinfo = &psrio->portpool[port_num].port_info; fsl_srio_connection(sriodev,port_num); if (fsl_srio_port_connected(sriodev) & (0x1 << port_num)) { fsl_srio_get_port_info(sriodev, port_num+1, pinfo, &range); psrio->portpool[port_num].range_virt = range; FVL_LOG("Get port %u info, range=%p, range_start=%llx ,range_size=%llx\n", port_num, range, pinfo->range_start,pinfo->range_size); } else { FVL_LOG("%s(): fsl_srio_connection port %d failed\n", __func__, port_num+1); return -1; } rvl = fsl_srio_port_connected(sriodev); if (rvl <= 0) { FVL_LOG("%s(): fsl_srio_port_connected return %d\n", __func__, rvl); return -1; } FVL_LOG("*****************************************************\n"); rvl = dma_pool_init(&port_dma_ctl_wp,ctl_win_size,ctl_win_size/2); if(rvl!=0) { FVL_LOG("port %d dma_pool_init failed!\n",port_num+1); return -errno; } rvl = dma_pool_init(&port_dma_ctl_wr,ctl_win_size,ctl_win_size/2); if(rvl!=0) { FVL_LOG("port %d dma_pool_init failed!\n",port_num+1); return -errno; } FVL_LOG("*********************dma pool init end**************\n"); uint32_t attr_read, attr_write; attr_read = srio_test_win_attrv[3]; attr_write = srio_test_win_attrv[0]; FVL_LOG("attr_write = %u, srio_type = 0\n", attr_write); ppool = &psrio->portpool[port_num]; ppool->write_result = port_dma_wr->dma_phys_base; ppool->pwrite_result = port_dma_wr->dma_virt_base; ppool->write_ctl_result = port_dma_ctl_wr->dma_phys_base; ppool->write_ctl_data = port_dma_ctl_wp->dma_phys_base; ppool->pwrite_ctl_result = port_dma_ctl_wr->dma_virt_base; ppool->pwrite_ctl_data = port_dma_ctl_wp->dma_virt_base; ctl_law=FVL_BASE_LAW+fvl_get_law((ctl_win_size/FVL_BASE_LAW_SIZE)-1); FVL_LOG("ctl law:%d\n",ctl_law); fsl_srio_set_ibwin(sriodev, port_num, 2, ppool->write_ctl_result, FVL_SRIO_CTL_ADDR, ctl_law); rvl=fsl_srio_set_deviceid(sriodev,port_num,source_id[port_num]); if(rvl!=0) { FVL_LOG("SRIO port %d set source_id faile!\n",port_num); return -errno; } rvl=fsl_srio_set_targetid(sriodev,port_num,1,target_id[port_num]); if(rvl!=0) { FVL_LOG("SRIO port %d set target_id faile!\n",port_num); return -errno; } rvl=fsl_srio_set_targetid(sriodev,port_num,2,target_id[port_num]); if(rvl!=0) { FVL_LOG("SRIO port %d set target_id faile!\n",port_num); return -errno; } fsl_srio_set_err_rate_degraded_threshold(sriodev,port_num,0); fsl_srio_set_err_rate_failed_threshold(sriodev,port_num,0); fsl_srio_set_phy_retry_threshold(sriodev,port_num,0,0); memset(port_dma_wr->dma_virt_base,0x5a,win_size); memset(port_dma_ctl_wp->dma_virt_base,0,ctl_win_size); memset(port_dma_ctl_wr->dma_virt_base,0,ctl_win_size); fvl_srio_channel_t *temp_channel; for(i=0;i<FVL_PORT_CHAN_NUM_MAX;i++) { pscb=fvl_srio_getcb(port_num,i*2); if(pscb==NULL) { FVL_LOG("port:%d channel:%d : dmadev init error.\n",port_num+1,2*i); return -1; } temp_channel=&srio_channel_context[FVL_PORT_CHAN_NUM_MAX*port_num+i]; cscb=&(temp_channel->chanblk); cscb->dmadev=pscb->dmadev; cscb->bfnum=pscb->bfnum; cscb->port = pscb->port; pscb=fvl_srio_getcb(port_num,i*2+1); if(pscb==NULL) { FVL_LOG("port:%d channel:%d : dmadev init error.\n",port_num+1,2*i+1); return -1; } re_cscb=&(temp_channel->rechanblk); re_cscb->dmadev=pscb->dmadev; re_cscb->bfnum=pscb->bfnum; re_cscb->port = pscb->port; } //create thread: FVL_LOG("port_num:%d\n",port_num); head_arg[port_num].num = port_num; head_arg[port_num].cpu = port_num+1; head_arg[port_num].op_mode = 0; head_arg[port_num].buf_virt=ppool->pwrite_ctl_result; rvl = pthread_create(&(psrio->chan_id[port_num]), NULL,fvl_srio_recv_head, &head_arg[port_num]); if (rvl) { FVL_LOG("Create receive packet thread error!\n"); return -errno; } FVL_LOG("SRIO Initial complete\n"); return 0; }
int fvl_srio_channel_open(char *name) { int fd=0; int rvl=0,i=0; fvl_srio_context_t *psrio = &g_srio_context; fvl_srio_portpool_t *cpool; fvl_srio_portpool_t *ppool; fvl_srio_ctrlblk_t *pscb; fvl_head_thread_t head_p_arg; int port_num=0,chan_size=0,ctl_size=0,bfnum=0; uint32_t offset=0,ctl_offset=0; fd=fvl_get_channel(name); if(fd==-1) { FVL_LOG("open error:channel name error.\n"); return -1; } port_num=srio_ctable_context[fd].port; bfnum = srio_ctable_context[fd].chan; if(bfnum > psrio->chan_num[port_num]) { FVL_LOG("open error:channel not exist.\n"); return -1; } FVL_LOG("************************************************\n"); FVL_LOG("port_num:%d uflag:%d\n",port_num,head_port[port_num].uflag); volatile uint8_t *flag= &head_port[port_num].uflag; while(1) { fflush(stdout); if(*flag) { break; } } rese_num[fd]=head_port[port_num].data_se_cluster[(fd%FVL_PORT_CHAN_NUM_MAX)].buf_num; //end mode master FVL_LOG("*****after while ****Head_size:%d rese_num:%d \n",HEAD_SIZE,rese_num[fd]); ctl_size = FVL_CTL_WIN_SIZE; ctl_offset=ctl_size*bfnum; for(i=0;i<bfnum;i++) { offset=offset+srio_channel_context[i].chan_size; } FVL_LOG("offset:%08x\n",offset); fvl_srio_channel_t *temp_channel; temp_channel=&srio_channel_context[fd]; cpool=&(temp_channel->chanpool); pscb=&(temp_channel->chanblk); ppool = &psrio->portpool[port_num]; cpool->write_result = ppool->write_result+offset; cpool->pwrite_result = ppool->pwrite_result+offset; cpool->write_ctl_result = ppool->write_ctl_result+HEAD_SIZE+ctl_offset; cpool->write_ctl_data = ppool->write_ctl_data+HEAD_SIZE+ctl_offset; cpool->pwrite_ctl_result = ppool->pwrite_ctl_result+HEAD_SIZE+ctl_offset; cpool->pwrite_ctl_data = ppool->pwrite_ctl_data+HEAD_SIZE+ctl_offset; // very important cpool->port_info.range_start=ppool->port_info.range_start+offset; cpool->ctl_info_start = ppool->ctl_info_start+HEAD_SIZE+ctl_offset; uint64_t dest_phys,src_phys; FVL_LOG("##### channel:%d Slave receive ctl_head info!\n",fd); dest_phys=cpool->ctl_info_start; src_phys=cpool->write_ctl_data; memcpy(cpool->pwrite_ctl_data,&head_channel[fd],HEAD_SIZE); fvl_srio_send(pscb->dmadev,src_phys,dest_phys,HEAD_SIZE); FVL_LOG("##### channel:%d Slave reback ctl_head info!\n",fd); // add ctl_re_arg[fd].fd=fd; ctl_re_arg[fd].port_num=port_num; ctl_re_arg[fd].cpu=fd+3; ctl_re_arg[fd].buf_virt=cpool->pwrite_ctl_result+FVL_SRIO_RD_OP*HEAD_SIZE; rvl = pthread_create(&(temp_channel->chan_id), NULL,fvl_srio_recv_ctl, &ctl_re_arg[fd]); if (rvl) { FVL_LOG("Create receive packet thread error!\n"); return -errno; } return fd; }
int main(int argc, char *argv[]){ int N, i, rc; str_tiratore *tiratore; void *status; pthread_attr_t attr; if(argc!=5){ printf("Numero dei parametri inseriti errato....\n"); exit(EXIT_FAILURE); } N=atoi(argv[1]); //numero appassionati di tiro con l'arco K=atoi(argv[2]); //numero dei tiri a disposizione A=atoi(argv[3]); //numero di archi I=atoi(argv[4]); //numero di freccie if((N<10)||(N>30)||(A<1)||(A>3)||(I<3)||(I>6)){ printf("NON consentito\n"); exit(-1); } tiratore=(str_tiratore *)malloc(N*sizeof(str_tiratore)); //inizializzazione semafori sem_init(&archi,0,A); //semaforo x gli archi sem_init(&freccie,0,I); //semaforo per le freccie //inizializzazione mutex pthread_mutex_init(&bersaglio, NULL); //inizializzazione dei thread pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); for(i=0; i<N; i++){ tiratore[i].id=i; tiratore[i].parziale=0; tiratore[i].totale=0; rc=pthread_create(&tiratore[i].tid,&attr,routine_tiro,(void *)(&tiratore[i])); if(rc){ printf("ERRORE.....\n"); getchar(); //premere invio exit(-1);} } rc=pthread_create(&gestore,&attr,routine_gestore,NULL); if(rc){ printf("ERRORE.....\n"); getchar(); //premere invio exit(-1);} //rilascio delle risorse per i thread pthread_attr_destroy(&attr); for(i=0; i<N; i++) pthread_join(tiratore[i].tid,&status); //si attende che finiscano tutti i thread printf("\n CLASSIFICA \n"); for(i=0; i<N; i++){ printf("tiratore %d, ha totalizzato %d punti\n",tiratore[i].id,tiratore[i].totale); } //rilascio delle risorse per il mutex pthread_mutex_destroy(&bersaglio); //rilascio delle risorse per i semafori sem_destroy(&archi); sem_destroy(&freccie); pthread_exit(NULL); }
//------------------------------------------------------------------------------ tOplkError edrv_init(const tEdrvInitParam* pEdrvInitParam_p) { struct sched_param schedParam; // Check parameter validity ASSERT(pEdrvInitParam_p != NULL); // clear instance structure OPLK_MEMSET(&edrvInstance_l, 0, sizeof(edrvInstance_l)); if (pEdrvInitParam_p->pDevName == NULL) return kErrorEdrvInit; // save the init data edrvInstance_l.initParam = *pEdrvInitParam_p; /* if no MAC address was specified read MAC address of used * Ethernet interface */ if ((edrvInstance_l.initParam.aMacAddr[0] == 0) && (edrvInstance_l.initParam.aMacAddr[1] == 0) && (edrvInstance_l.initParam.aMacAddr[2] == 0) && (edrvInstance_l.initParam.aMacAddr[3] == 0) && (edrvInstance_l.initParam.aMacAddr[4] == 0) && (edrvInstance_l.initParam.aMacAddr[5] == 0)) { // read MAC address from controller getMacAdrs(edrvInstance_l.initParam.pDevName, edrvInstance_l.initParam.aMacAddr); } // Set up and activate the pcap live capture handle edrvInstance_l.pPcap = startPcap(); if (edrvInstance_l.pPcap == NULL) { return kErrorEdrvInit; } if (pcap_setdirection(edrvInstance_l.pPcap, PCAP_D_OUT) < 0) { DEBUG_LVL_ERROR_TRACE("%s() couldn't set PCAP direction\n", __func__); return kErrorEdrvInit; } if (pthread_mutex_init(&edrvInstance_l.mutex, NULL) != 0) { DEBUG_LVL_ERROR_TRACE("%s() couldn't init mutex\n", __func__); return kErrorEdrvInit; } if (sem_init(&edrvInstance_l.syncSem, 0, 0) != 0) { DEBUG_LVL_ERROR_TRACE("%s() couldn't init semaphore\n", __func__); return kErrorEdrvInit; } if (pthread_create(&edrvInstance_l.hThread, NULL, workerThread, &edrvInstance_l) != 0) { DEBUG_LVL_ERROR_TRACE("%s() Couldn't create worker thread!\n", __func__); return kErrorEdrvInit; } schedParam.sched_priority = CONFIG_THREAD_PRIORITY_MEDIUM; if (pthread_setschedparam(edrvInstance_l.hThread, SCHED_FIFO, &schedParam) != 0) { DEBUG_LVL_ERROR_TRACE("%s() couldn't set thread scheduling parameters!\n", __func__); } #if (defined(__GLIBC__) && (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 12)) pthread_setname_np(edrvInstance_l.hThread, "oplk-edrvpcap"); #endif /* wait until thread is started */ sem_wait(&edrvInstance_l.syncSem); return kErrorOk; }
int main() { socket_init(); fp1 = fopen("raw_recv_data.txt","w"); fp2 = fopen("increase_bit.txt","w"); printf("my:hello fedora!\n"); if((testfd = ML605Open())<0) printf("open ml605 failed"); if(ML605StartEthernet(testfd, SFP_TX_START)<0) { printf("PCIe:Start ethernet failure\n"); ML605Close(testfd); exit(-1); } /* pthread_t writethread; if (pthread_create(&writethread, NULL, mywrite, NULL)) { perror("writethread process thread creation failed"); } sleep(1); */ /* pthread_t readthread; if (pthread_create(&readthread, NULL, GetRate, NULL)) { perror("readthread process thread creation failed"); } sleep(1); */ pthread_t ratathread; /* if (pthread_create(&ratathread, NULL, myread2, NULL)) { perror("readthread process thread creation failed"); } pthread_t readthread2; if (pthread_create(&ratathread, NULL, myread, NULL)) { perror("readthread process thread creation failed"); } */ pthread_t readthread3; if (pthread_create(&ratathread, NULL, myread3, NULL)) { perror("readthread process thread creation failed"); } sleep(1); char ch_input; scanf("%c", &ch_input); isclose=0; ML605Close(testfd); fclose(fp1); fclose(fp2); }
int main(int argc, char **argv) { int err_ret, sin_size; struct sockaddr_in serv_addr, client_addr; pthread_t interrupt; list_init(&client_list);//initialize linked list pthread_mutex_init(&clientlist_mutex, NULL);//initiate mutex if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {//avoir le socket err_ret = errno; fprintf(stderr, "socket() failed...\n"); return err_ret; } /*set initiate values*/ serv_addr.sin_family = AF_INET;//@family=internet serv_addr.sin_port = htons(PORT); serv_addr.sin_addr.s_addr = inet_addr(IP);//set l @ IP to local host memset(&(serv_addr.sin_zero), 0, 8); if(bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) == -1) {//reserver le port sur lequel on veut secouter err_ret = errno; fprintf(stderr, "bind() failed...\n"); return err_ret; } /*start listen with max connection*/ if(listen(sockfd, BACKLOG) == -1) { err_ret = errno; fprintf(stderr, "listen() failed...\n"); return err_ret; } /*initiate interrupt handler for IO controlling */ printf("Starting server...\n"); if(pthread_create(&interrupt, NULL, io_handler, NULL) != 0) { err_ret = errno; fprintf(stderr, "pthread_create() failed...\n"); return err_ret; } /*on accepte la connexion */ printf("accepting connections...\n"); while(1) { sin_size = sizeof(struct sockaddr_in); if((newfd = accept(sockfd, (struct sockaddr *)&client_addr, (socklen_t*)&sin_size)) == -1) { err_ret = errno; fprintf(stderr, "accept() failed...\n"); return err_ret; } else { if(client_list.size == CLIENTS) { fprintf(stderr, "Connection full, request rejected...\n"); continue; } printf("Connection requested received...\n"); struct THREADINFO threadinfo; threadinfo.sockfd = newfd; strcpy(threadinfo.alias, "Anonymous"); pthread_mutex_lock(&clientlist_mutex); list_insert(&client_list, &threadinfo); pthread_mutex_unlock(&clientlist_mutex); pthread_create(&threadinfo.thread_ID, NULL, client_handler, (void *)&threadinfo); } } return 0; }
int main(int argc, char *argv[ ]) { tree *bst = NULL; int input[ 5000 ]; char input_num[MAX]; char *temp; char *temp2; int b[MAX]; int try[5] = {5,4,3,2,1}; int i=0, num, req; int j = 0; int count = 0; int check = 0; int input_size = 0; int a[MAX] = {0}; int test; char get_ch ; // FILE pointer of reading and writing // and thread_t FILE *fp; FILE *fw; // check the arguments if it is exactly three /* if(argc != 3){ perror("parameter amount error!"); return 0; } */ // open two files for read input and write output fp = fopen(argv[1], "r"); //fw = fopen(argv[2], "a"); /* while( (get_ch = fgetc(fp)) != EOF ){ printf("this character: %s\n",get_ch); if( get_ch != ) count ++; } */ while( fgets(input_num,MAX,fp) != NULL ) { printf("this is count: %d\n", count); temp = strtok(input_num," "); while( temp != NULL){ printf("%s\n",temp); //printf("test\n"); if(count == 0){ b[i] = atoi(temp); //printf("what is b[%d] ? %d\n",i,b[i]); i++; check++; }else{ input[j] = atoi(temp); j++; input_size++; } //printf("%s ",temp); temp = strtok(NULL, " "); } //char temp[10]; count++; } i = 0; j = 0; // arr to catch the "to search numbers" // the value of the array "arr" is the number to search in the bst int arr[check]; //printf("\n\ncheck: %d\n",check); for(j=0;j<check;++j){ arr[j] = b[j]; printf(" array arr value: %d \n",arr[j]); } printf("the total input numbers' size: %d\n",input_size); for(i=0;i<input_size;i++) printf("input[%d] , value: %d\n",i,input[i]); // create thread according to the number of int's on the first line pthread_t threads[check]; // thread_data_t type structture initialize thread_data_t thr_data[check]; // check the thread ids int check_thread[check]; for(i=0;i<check;++i){ thr_data[i].amount = input_size; thr_data[i].tid = i; thr_data[i].search_num = arr[i]; thr_data[i].arg = argv[2]; for(j=0;j<thr_data[i].amount;++j){ thr_data[i].list[j] = input[j]; } if( (check_thread[i] = pthread_create(&threads[i], NULL, thr_func, &thr_data[i])) ){ fprintf(stderr,"error: pthread_create, thread: %d\n",check_thread[i]); return EXIT_FAILURE; } } // insert the array into the tree // print out the data in the inorder fashion //inorder(bst); printf("\n"); // to open a file // while to insert pthread_exit(NULL); fclose(fp); fclose(fw); return 0; } // the functnio that the threads need to do. void *thr_func(void *arg) { thread_data_t *data = (thread_data_t *)arg; //printf("hello thread, you are thread %d, value: %d\n",data->tid,data->search_num); tree *node = NULL; int k ; // construct tree: insert all node into the tree for( k = 0; k<data->amount; k++ ){ node = insert(node, data->list[k]); } //inorder(node); // search tree: int num = 0; //int a = data->amount; //int search_arr[data->] = {0}; for( k = 0 ; k < data->amount ; k++){ if( (data->list[k]) == (data->search_num) ){ if( (node = search(node, data->search_num))!= NULL){ num = num + 1; } } } data->total = num; printf("number of same: %d\n", num); FILE *fptr; fptr = fopen(data->arg,"a"); fprintf(fptr,"search number: %d, the amount: %d\n", data->search_num, num); pthread_exit("thread exit success\n"); } tree *find_min( tree *node ) { tree * current; current = node; while(current->leftchild != NULL) current = current->rightchild; return current; }
int main (int argc, char **argv) { if(argc > 1) { //fprintf(stdout,"%s\n",argv[1]); int server_fd; unsigned short remote_port; remote_port = 8000; struct sockaddr_in remote_ipv4_address; memset(&remote_ipv4_address,0,sizeof(remote_ipv4_address)); remote_ipv4_address.sin_family = AF_INET; remote_ipv4_address.sin_port = htons(remote_port); inet_pton(AF_INET,argv[1],&remote_ipv4_address.sin_addr); //pause(); ssize_t receive; ssize_t total = 0; ssize_t send; char buffer[BUFFER_SIZE]; while(1) { if((server_fd = socket(PF_INET,SOCK_STREAM,0)) < 0){ fprintf(stderr,"socket create failed,%s\n",strerror(errno)); exit(1); } fprintf(stdout,"Socket create successed,server fd %d\n",server_fd); if(connect(server_fd,(struct sockaddr *)&remote_ipv4_address,sizeof(remote_ipv4_address)) < 0){ fprintf(stderr,"connect to remote server %s : %d failed,%s\n",argv[1],remote_port,strerror(errno)); close(server_fd); exit(1); } fprintf(stdout,"Connected to %s:%d success.\n",argv[1],remote_port); receive = read(STDIN_FILENO,buffer,sizeof(buffer)); if(strncmp(buffer,"ls",2) == 0){ send = write(server_fd,buffer,receive); if(send < 0){ fprintf(stderr,"send command to server failed,%s\n",strerror(errno)); exit(2); } fprintf(stdout,"Send %d bytes to server successed.\n",send); while(1) { receive = read(server_fd,buffer,BUFFER_SIZE - 1); if(receive < 0){ if(errno == EINTR) continue; fprintf(stderr,"receive data failed,%s\n",strerror(errno)); exit(3); }else if(receive == 0){ break; } write(STDOUT_FILENO,buffer,receive); total += receive; } fprintf(stdout,"Received %d bytes.\n",total); total = 0; }else if(strncmp(buffer,"cp",2) == 0){ total = 0; send = write(server_fd,buffer,receive); if(send < 0){ fprintf(stderr,"send command to server failed,%s\n",strerror(errno)); exit(2); } fprintf(stdout,"Send %d bytes to server successed.\n",send); char rbuffer[BUFFER_SIZE]; receive = read(server_fd,rbuffer,BUFFER_SIZE - 1); if(strncmp(rbuffer,"Bad",3) == 0){ write(STDOUT_FILENO,rbuffer,receive); exit(3); } if(strncmp(rbuffer,"File",4) == 0){ write(STDOUT_FILENO,rbuffer,receive); exit(3); } char *ptr; buffer[send - 1] = '\0'; fprintf(stdout,"%s\n",buffer); ptr = str_proc(buffer + 2); if(ptr == NULL){ fprintf(stderr,"string process failed\n"); exit(3); } char path[4096]; snprintf(path,sizeof(path),"./res/jpg/%s",ptr); fprintf(stdout,"path %s\n",path); int file_fd = open(path,O_RDWR | O_CREAT | O_TRUNC,0644); if(file_fd < 0){ fprintf(stderr,"open file %s failed,%s\n",path,strerror(errno)); exit(3); } write(file_fd,rbuffer,receive); total += receive; while((receive = read(server_fd,rbuffer,BUFFER_SIZE - 1)) != 0) { write(file_fd,rbuffer,receive); total += receive; } fprintf(stdout,"Download success.Received %d bytes.\n",total); close(file_fd); }else if(strncmp(buffer,"exit",4) == 0){ break; } close(server_fd); } } else{ if(init_fb(&fb_inf) < 0){ fprintf(stderr,"init fb failed,%s\n",strerror(errno)); exit(1); } screen_size = fb_inf.w * fb_inf.h * fb_inf.bpp / 8; fprintf(stdout,"%d\n",screen_size); int err_code; #if 1 pthread_t mou_tid; if((err_code = pthread_create(&mou_tid,NULL,mouse_ops,NULL)) != 0 ) { fprintf(stderr,"create pthread failed,%s\n",strerror(err_code)); exit(5); } #endif #if 1 char *file_desk[1024]; int pic_num = 0; if(read_jpg_dir("./res/jpg",file_desk,&pic_num) < 0){ fprintf(stderr,"read_jpg_dir failed.\n"); int pic_num = 0; if(read_jpg_dir("./res/jpg",file_desk,&pic_num) < 0){ fprintf(stderr,"read_jpg_dir failed.\n"); exit(4); } exit(4); } tranves_file_desk(file_desk,pic_num); fprintf(stdout,"sum %d\n",pic_num); #if 1 err_code = init_ft("./res/fonts/fanxinshu.TTF",36); if(err_code != 0){ fprintf(stderr,"init_ft failed\n"); exit(1); } #endif fun play_funs[DISPLAY_FUNS] = {disp_jpeg2,fang_picture_l,right_mid_left,fang_picture_h,down_in,right_in,bai_ye_chuang,up_down,left_right,rand_picture,crilepicture_big,crilepicture_small,up_mid_down,left_fix_right,Random,Box_radom,dissolve}; unsigned int index = 0; unsigned int fun_ind = 0; int flag = 1; char pathname[1024]; welcome_menu: rool_flag = 0; welcome_flag = 1; #if 1 err_code = init_ft("./res/fonts/fanxinshu.TTF",36); if(err_code != 0){ fprintf(stderr,"init_ft failed\n"); exit(1); } #endif pthread_mutex_lock(&mutex_lock); play_funs[0]("./res/welcome/welcome.jpg",fb_inf); display_string("自动播放",200,200,fb_inf,0x0930e); display_string("手动播放",400,400,fb_inf,0xc9112d); display_string("音乐播放",600,600,fb_inf,0xe68500); display_string("退出",950,750,fb_inf,0x9f0521); memcpy(screen_save,fb_inf.fbmem,screen_size); pthread_mutex_unlock(&mutex_lock); while(!rool_flag) sleep(1); welcome_flag = 0; while(flag == 1) { //fprintf(stdout,"%s,%d,flag %d\n",pathname,fun_ind,mouse_global_flag); #if 1 switch(mouse_global_flag) { case 0: #if 1 snprintf(pathname,sizeof(pathname),"./res/jpg/%s",file_desk[index]); pthread_mutex_lock(&mutex_lock); play_funs[fun_ind](pathname,fb_inf); init_ft("./res/fonts/fanxinshu.TTF",22); display_string(file_desk[index],10,20,fb_inf,0xaffff); memcpy(screen_save,fb_inf.fbmem,screen_size); pthread_mutex_unlock(&mutex_lock); fun_ind++; fun_ind = fun_ind % DISPLAY_FUNS; index++; index = index % pic_num; #endif sleep(1); break; case 1: index++; index = index % pic_num; snprintf(pathname,sizeof(pathname),"./res/jpg/%s",file_desk[index]); pthread_mutex_lock(&mutex_lock); play_funs[15](pathname,fb_inf); init_ft("./res/fonts/stsong.ttf",30); display_string("返回",950,750,fb_inf,0x9f0521); init_ft("./res/fonts/fanxinshu.TTF",22); display_string(file_desk[index],10,20,fb_inf,0xaffff); memcpy(screen_save,fb_inf.fbmem,screen_size); pthread_mutex_unlock(&mutex_lock); mouse_global_flag = 10; sleep(1); break; case -1: index--; index = index % pic_num; snprintf(pathname,sizeof(pathname),"./res/jpg/%s",file_desk[index]); pthread_mutex_lock(&mutex_lock); play_funs[16](pathname,fb_inf); init_ft("./res/fonts/stsong.ttf",30); display_string("返回",950,750,fb_inf,0x9f0521); init_ft("./res/fonts/fanxinshu.TTF",22); display_string(file_desk[index],10,20,fb_inf,0xaffff); memcpy(screen_save,fb_inf.fbmem,screen_size); pthread_mutex_unlock(&mutex_lock); mouse_global_flag = 10; sleep(1); break; case 2: goto welcome_menu; break; case 3: flag = 0; break; default: break; } #endif } pthread_mutex_lock(&mutex_lock); play_funs[9]("./res/end/end.jpg",fb_inf); init_ft("./res/fonts/fanxinshu.TTF",90); display_string("谢谢观赏",360,300,fb_inf,0xb8264a); memcpy(screen_save,fb_inf.fbmem,screen_size); pthread_mutex_unlock(&mutex_lock); pthread_mutex_destroy(&mutex_lock); pthread_cancel(mou_tid); pthread_join(mou_tid,NULL); destroy_file_desk(file_desk,pic_num); #endif if(munmap(fb_inf.fbmem,fb_inf.w * fb_inf.h * fb_inf.bpp / 8) < 0){ fprintf(stderr,"mmunmap failed,%s\n",strerror(errno)); exit(5); } } return 0; }
bool Thread::start(classID (threadFunction)(classID), classID parameter){ //kill the previous thread this->kill(); //test if the function is true if(threadFunction){ //WINDOWS 32 #ifdef WIN32 DWORD flag; this->threadID = CreateThread(NULL, // (DWORD)NULL, // edkThreadFunc, // função da thread (void*)this, // parâmetro da thread (DWORD)NULL, // &flag); //test if create the thread if(this->threadID!=(HANDLE)0u){ #elif defined WIN64 //WINDOWS 64 DWORD flag; this->threadID = CreateThread(NULL, // (DWORD)NULL, // edkThreadFunc, // função da thread (void*)this, // parâmetro da thread (DWORD)NULL, // &flag); //test if create the thread if(this->threadID!=(HANDLE)0u){ #elif defined __linux__ //LINUX pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&threadID, &attr, edkThreadFunc, (void*)this); //test if create the thread if(this->threadID!=(pthread_t)0u){ #elif defined __APPLE__ //APPLE #endif //copy the function this->threadFunc=threadFunction; //copy the parameter this->funcParameter=parameter; //then return true; return true; } } //clean this->cleanThread(); //else he clean the func this->threadFunc=NULL; return false; } bool Thread::start(classID (threadFunction)(classID)){ return this->start(threadFunction,(void*)NULL); } bool Thread::startIn(classID (threadFunction)(classID), classID parameter, edk::uint32 core){ //kill the previous thread this->kill(); //test if the function is true and if the core exist if(threadFunction && core<this->cores){ //WINDOWS 32 #ifdef WIN32 DWORD flag; this->threadID = CreateThread(NULL, // (DWORD)NULL, // edkThreadFunc, // função da thread (void*)this, // parâmetro da thread (DWORD)NULL, // &flag); //test if create the thread if(this->threadID!=(HANDLE)0u){ DWORD_PTR mask = core; SetThreadAffinityMask(this->threadID, mask); #elif defined WIN64 //WINDOWS 64 DWORD flag; this->threadID = CreateThread(NULL, // (DWORD)NULL, // edkThreadFunc, // função da thread (void*)this, // parâmetro da thread (DWORD)NULL, // &flag); //test if create the thread if(this->threadID!=(HANDLE)0u){ DWORD_PTR mask = core; SetThreadAffinityMask(this->threadID, mask); #elif defined __linux__ //LINUX pthread_attr_t attr; CPU_SET(core, &this->cpus); //start the attribute pthread_attr_init(&attr); //set the core on the attribute pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &this->cpus); //set affinity pthread_create(&threadID, &attr, edkThreadFunc, (void*)this); //test if create the thread if(this->threadID!=(pthread_t)0u){ #elif defined __APPLE__ //APPLE #endif //copy the function this->threadFunc=threadFunction; //copy the parameter this->funcParameter=parameter; //then return true; return true; } } //clean this->cleanThread(); //else he clean the func this->threadFunc=NULL; return false; } bool Thread::startIn(classID (threadFunction)(classID), edk::uint32 core){ return this->startIn(threadFunction, NULL, core); } //change the threadCore bool Thread::changeCore(edk::uint32 core){ //test if have the core if(core<this->cores){ #ifdef WIN32 //test if create the thread if(this->threadID!=(HANDLE)0u){ DWORD_PTR mask = core; if(SetThreadAffinityMask(this->threadID, mask)){ return true; #elif defined WIN64 //WINDOWS 64 //test if create the thread if(this->threadID!=(HANDLE)0u){ DWORD_PTR mask = core; if(SetThreadAffinityMask(this->threadID, mask)){ return true; #elif defined __linux__ //test if have the thread if(this->threadID!=(pthread_t)0u){ CPU_ZERO(&this->cpus); CPU_SET(core, &this->cpus); //set the core if(!pthread_setaffinity_np(this->threadID,sizeof(cpu_set_t), &this->cpus)){ return true; } #elif defined __APPLE__ //APPLE #endif } } return false; } bool Thread::runFunc(){ if(this->threadFunc){ //test if have parameter if(this->funcParameter){ //then he cant run the function this->threadFunc((void*)this->funcParameter); } else{ //then he cant run the function this->threadFunc((void*)NULL); } //clean the function this->threadFunc=NULL; this->funcParameter=NULL; //return true; return true; } //else return false return false; } bool Thread::isAlive(){ //WINDOWS 32 #ifdef WIN32 if(this->threadID){ //Then wait for the thread if(WaitForSingleObject(threadID, 0u) == WAIT_TIMEOUT){ //thread still alive return true return true; } } #elif defined WIN64 //WINDOWS 64 if(this->threadID){ //Then wait for the thread if(WaitForSingleObject(threadID, 0u) == WAIT_TIMEOUT){ //thread still alive return true return true; } } #elif defined __linux__ //WINDOWS 64 if(this->threadID){ //Then wait for the thread if(pthread_kill(this->threadID, 0u)!=3u){ //thread still alive return true return true; } } #elif defined __APPLE__ //APPLE #endif //else return false; return false; } bool Thread::waitEnd(uint64 milliseconds){ //WINDOWS 32 #ifdef WIN32 if(this->threadID){ //Then wait for the thread if(WaitForSingleObject(threadID, milliseconds) == WAIT_TIMEOUT){ //thread still alive then return true; } } #elif defined WIN64 //WINDOWS 64 if(this->threadID){ //Then wait for the thread if(WaitForSingleObject(threadID, milliseconds) == WAIT_TIMEOUT){ //thread still alive then return true; } } #elif defined __linux__//Linux //first he sleep usleep(milliseconds*1000); //test if thread still alive if(this->isAlive()){ // return true; } #elif __APPLE__ //APPLE #endif //clean this->cleanThread(); //else return false; return false; } bool Thread::waitEnd(){ bool ret=false; //WINDOWS 32 #ifdef WIN32 if(this->threadID){ //Then wait for the thread WaitForSingleObject(threadID, INFINITE); //then return true ret = true; } #elif defined WIN64 //WINDOWS 64 if(this->threadID){ //Then wait for the thread WaitForSingleObject(threadID, INFINITE); //then return true ret = true; } #elif defined __linux__ //LINUX if(this->threadID){ //then wait the end of the thread pthread_join(this->threadID,NULL); //then return true ret = true; } #elif defined __APPLE__ //APPLE #endif //clean this->cleanThread(); //return true or false return ret; } bool Thread::kill(){ bool ret = false; //WINDOWS 32 #ifdef WIN32 if(this->threadID){ //Finish the thread TerminateThread(this->threadID ,(DWORD)NULL ); ret=true; } //clean ID this->threadID=(HANDLE)0u; #elif defined WIN64 //WINDOWS 64 if(this->threadID){ //Finish the thread TerminateThread(this->threadID ,(DWORD)NULL ); ret=true; } #elif defined __linux__ //LINUX if(this->threadID){ //Cancel the thread pthread_cancel(this->threadID); //pthread_attr_destroy(&attr); //Finish the thread ret=true; } #endif //clean this->cleanThread(); //return true or false return ret; } void Thread::killThisThread(){ //WINDOWS 32 #ifdef WIN32 //Finish the thread TerminateThread(NULL ,(DWORD)NULL ); #elif defined WIN64 //WINDOWS 64 //Finish the thread TerminateThread(NULL ,(DWORD)NULL ); #elif defined __linux__ //LINUX //Exit the process pthread_exit(NULL); #elif defined __linux__ //APPLE //Exit the process pthread_exit(NULL); #endif } void Thread::killAllThreads(){ //WINDOWS 32 #ifdef WIN32 /* //Finish the thread TerminateThread(NULL ,(DWORD)NULL ); */ #elif defined WIN64 //WINDOWS 64 /* //Finish the thread TerminateThread(NULL ,(DWORD)NULL ); */ #elif defined __linux__ //LINUX //Exit the process pthread_cancel((pthread_t)NULL); #elif defined __linux__ //APPLE //Exit the process pthread_cancel((pthread_t)NULL); #endif } #if __x86_64__ || __ppc64__ //get the thread id edk::uint64 Thread::getThisThreadID(){ #if WIN64 return GetCurrentThreadId(); #elif __linux__ return pthread_self(); #endif } #else //get the thread id edk::uint32 Thread::getThisThreadID(){ #if WIN32 return GetCurrentThreadId(); #elif __linux__ return pthread_self(); #endif } #endif //return the thread core edk::uint32 Thread::getThisThreadCore(){ #if defined(WIN32) || defined(WIN64) return 0; #elif __linux__ return sched_getcpu(); #endif } edk::uint32 Thread::numberOfCores(){ return edk::multi::Thread::cores; } }
/** * Initialize the navdata board */ bool navdata_init() { assert(sizeof(struct navdata_measure_t) == NAVDATA_PACKET_SIZE); /* Check if the FD isn't already initialized */ if (navdata.fd <= 0) { navdata.fd = open("/dev/ttyO1", O_RDWR | O_NOCTTY); /* O_NONBLOCK doesn't work */ if (navdata.fd < 0) { printf("[navdata] Unable to open navdata board connection(/dev/ttyO1)\n"); return false; } /* Update the settings of the UART connection */ fcntl(navdata.fd, F_SETFL, 0); /* read calls are non blocking */ /* set port options */ struct termios options; /* Get the current options for the port */ tcgetattr(navdata.fd, &options); /* Set the baud rates to 460800 */ cfsetispeed(&options, B460800); cfsetospeed(&options, B460800); options.c_cflag |= (CLOCAL | CREAD); /* Enable the receiver and set local mode */ options.c_iflag = 0; /* clear input options */ options.c_lflag = 0; /* clear local options */ options.c_oflag &= ~OPOST; //clear output options (raw output) //Set the new options for the port tcsetattr(navdata.fd, TCSANOW, &options); } // Reset available flags navdata_available = false; navdata.baro_calibrated = false; navdata.baro_available = false; navdata.imu_lost = false; // Set all statistics to 0 navdata.checksum_errors = 0; navdata.lost_imu_frames = 0; navdata.totalBytesRead = 0; navdata.packetsRead = 0; navdata.last_packet_number = 0; /* Stop acquisition */ navdata_cmd_send(NAVDATA_CMD_STOP); /* Read the baro calibration(blocking) */ if (!navdata_baro_calib()) { printf("[navdata] Could not acquire baro calibration!\n"); return false; } navdata.baro_calibrated = true; /* Start acquisition */ navdata_cmd_send(NAVDATA_CMD_START); /* Set navboard gpio control */ gpio_setup_output(ARDRONE_GPIO_PORT, ARDRONE_GPIO_PIN_NAVDATA); gpio_set(ARDRONE_GPIO_PORT, ARDRONE_GPIO_PIN_NAVDATA); /* Start navdata reading thread */ pthread_t navdata_thread; if (pthread_create(&navdata_thread, NULL, navdata_read, NULL) != 0) { printf("[navdata] Could not create navdata reading thread!\n"); return false; } pthread_setname_np(navdata_thread, "pprz_navdata_thread"); #if PERIODIC_TELEMETRY register_periodic_telemetry(DefaultPeriodic, PPRZ_MSG_ID_ARDRONE_NAVDATA, send_navdata); #endif /* Set to initialized */ navdata.is_initialized = true; return true; }
int main(int argc, char *argv[]) { if (argc!=5) { fprintf(stderr, "Usage: in_file search_field id_field out_basename\n"); return 1; } char *in, *outbase; int in_len = strlen(argv[1]), out_len = strlen(argv[4]); in = malloc((in_len + 1) * sizeof(char)); if (!in) { fprintf(stderr, "failed to alloc 'in'\n"); return 1; } out_len += 1; outbase = malloc(out_len * sizeof(char)); if (!outbase) { fprintf(stderr, "failed to alloc 'outbase'\n"); return 1; } strcpy(in, argv[1]); strcpy(outbase, argv[4]); char *search_field, *id_field; int sf_len = strlen(argv[2]), idf_len = strlen(argv[3]); search_field = (char *) malloc((sf_len + 1) * sizeof(char)); if (!search_field) { fprintf(stderr, "failed to alloc 'search_field'\n"); return 1; } id_field = (char *) malloc((idf_len + 1) * sizeof(char)); if (!id_field) { fprintf(stderr, "failed to alloc 'id_field'\n"); return 1; } strcpy(search_field, argv[2]); strcpy(id_field, argv[3]); fprintf(stderr, "building indexes for %s...", in); struct chunks *chunks = NULL; struct indexes *indexes = NULL; if (!build_indexes(in, &indexes, &chunks, -1)) { fprintf(stderr, "failed to build indexes\n"); return 1; } fprintf(stderr, "done.\n"); char **out_files = malloc(sizeof(char *) * NUMCORES); if (!out_files) { fprintf(stderr, "failed to alloc out files\n"); return 1; } pthread_t *threads = malloc(sizeof(pthread_t) * NUMCORES); if (!threads) { fprintf(stderr, "failed to alloc threads\n"); return 1; } int *pt_ret = malloc(sizeof(int) * NUMCORES); if (!pt_ret) { fprintf(stderr, "failed to alloc pt_ret\n"); return 1; } struct find_field_args **args = malloc(sizeof(struct find_field_args *) * NUMCORES); if (!args) { fprintf(stderr, "failed to allocate args\n"); return 1; } char corestr[3]; int i, j; for (i=0; i<NUMCORES; i++) { sprintf(corestr, "%d", i); out_files[i] = malloc(sizeof(char) * (out_len + strlen(corestr) + 1)); if (!out_files[i]) { fprintf(stderr, "failed to alloc out file"); return 1; } strcpy(out_files[i], outbase); strcat(out_files[i], corestr); args[i] = malloc(sizeof(struct find_field_args)); args[i]->ioargs = malloc(sizeof(struct ioargs)); args[i]->ioargs->in_file = in; args[i]->ioargs->out_file = out_files[i]; args[i]->ioargs->chunk = &chunks[i]; args[i]->search_field = search_field; args[i]->id_field = id_field; int mb = args[i]->ioargs->chunk->size / (1024*1024); fprintf(stderr, "creating new thread[%d] to process %dMB of data\n", i, mb); pt_ret[i] = pthread_create(&threads[i], NULL, find_field, (void *) args[i]); } for (i=0; i<NUMCORES; i++) { pthread_join(threads[i], NULL); fprintf(stderr, "thread[%d] returned with status %d\n", i, pt_ret[i]); free(out_files[i]); free(args[i]->ioargs); free(args[i]); free_line_positions(chunks[i].lp); } if (indexes) { free_index(indexes->index); free_line_positions(indexes->lp); free(indexes); } free(chunks); free(out_files); free(args); free(in); free(outbase); free(search_field); free(id_field); free(pt_ret); free(threads); return 0; }
static void *xmi_random_thread(void *input) { unsigned long int temp_number; struct timespec sleep_time = {.tv_sec = (time_t) SLEEP_TIME,.tv_nsec = 0}; int rv; #if DEBUG == 2 fprintf(stdout,"Entering xmi_random_thread\n"); #endif //for loop keeps running until killed by xmi_end_random_acquisition for (;;) { //lock #if DEBUG == 2 fprintf(stdout,"Before lock in thread\n"); #endif rv=pthread_mutex_lock(&xmi_random_mutex); #if DEBUG == 2 fprintf(stdout,"After lock in thread: %i\n",rv); #endif if (xmi_numbers_in_memory < MAX_NUMBERS) { rv=pthread_mutex_unlock(&xmi_random_mutex); /* //open the random device if ((random_devicePtr=fopen(RANDOM_DEVICE,"r")) == NULL) { fprintf(stderr,"Could not open " RANDOM_DEVICE " for reading: continuing...\n"); nanosleep(&sleep_time,NULL); continue; }*/ #if DEBUG == 2 fprintf(stdout,"Before fread\n"); #endif if (fread(&temp_number,sizeof(unsigned long int),1,random_devicePtr) == 1) { rv=pthread_mutex_lock(&xmi_random_mutex); xmi_random_numbers[xmi_numbers_in_memory++]=temp_number; rv=pthread_mutex_unlock(&xmi_random_mutex); #if DEBUG == 2 fprintf(stdout,"Found a new number: %lu\n",temp_number); #endif } // fclose(random_devicePtr); } else { rv=pthread_mutex_unlock(&xmi_random_mutex); } #if DEBUG == 2 fprintf(stdout,"Before nanosleep: %i\n",rv); #endif nanosleep(&sleep_time,NULL); #if DEBUG == 2 fprintf(stdout,"After nanosleep\n"); #endif } //this line should never be reached return NULL; } int xmi_start_random_acquisition_dev(void) { #if DEBUG == 2 fprintf(stdout,"Entering xmi_start_random_acquisition\n"); #endif if (xmi_random_active == 1) { fprintf(stderr,"Random number acquisition already active\n"); return 0; } xmi_numbers_in_memory = 0; //allocate memory for the random_numbers xmi_random_numbers = (unsigned long int*) malloc(sizeof(unsigned long int)*MAX_NUMBERS); if (xmi_random_numbers == NULL) { fprintf(stderr,"Could not allocate memory for the random numbers\n"); return 0; } //open random device if ((random_devicePtr=fopen(RANDOM_DEVICE,"r")) == NULL) { fprintf(stderr,"Could not open " RANDOM_DEVICE " for reading\n"); return 0; } //initialize mutex pthread_mutex_init(&xmi_random_mutex,NULL); //start the thread if (pthread_create(&xmi_random_pthread_t, NULL, xmi_random_thread,NULL) != 0) { fprintf(stderr,"Could not create thread xmi_random_thread\n"); return 0; } xmi_random_active = 1; return 1; }
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/timer_create.html int timer_create(clockid_t clock_id, sigevent* evp, timer_t* timer_id) { PosixTimer* timer = reinterpret_cast<PosixTimer*>(malloc(sizeof(PosixTimer))); if (timer == NULL) { return -1; } timer->sigev_notify = (evp == NULL) ? SIGEV_SIGNAL : evp->sigev_notify; // If not a SIGEV_THREAD timer, the kernel can handle it without our help. if (timer->sigev_notify != SIGEV_THREAD) { if (__timer_create(clock_id, evp, &timer->kernel_timer_id) == -1) { free(timer); return -1; } *timer_id = timer; return 0; } // Otherwise, this must be SIGEV_THREAD timer... timer->callback = evp->sigev_notify_function; timer->callback_argument = evp->sigev_value; timer->armed = false; // Check arguments that the kernel doesn't care about but we do. if (timer->callback == NULL) { free(timer); errno = EINVAL; return -1; } // Create this timer's thread. pthread_attr_t thread_attributes; if (evp->sigev_notify_attributes == NULL) { pthread_attr_init(&thread_attributes); } else { thread_attributes = *reinterpret_cast<pthread_attr_t*>(evp->sigev_notify_attributes); } pthread_attr_setdetachstate(&thread_attributes, PTHREAD_CREATE_DETACHED); // We start the thread with TIMER_SIGNAL blocked by blocking the signal here and letting it // inherit. If it tried to block the signal itself, there would be a race. kernel_sigset_t sigset; sigaddset(sigset.get(), TIMER_SIGNAL); kernel_sigset_t old_sigset; pthread_sigmask(SIG_BLOCK, sigset.get(), old_sigset.get()); int rc = pthread_create(&timer->callback_thread, &thread_attributes, __timer_thread_start, timer); pthread_sigmask(SIG_SETMASK, old_sigset.get(), NULL); if (rc != 0) { free(timer); errno = rc; return -1; } sigevent se = *evp; se.sigev_signo = TIMER_SIGNAL; se.sigev_notify = SIGEV_THREAD_ID; se.sigev_notify_thread_id = pthread_gettid_np(timer->callback_thread); if (__timer_create(clock_id, &se, &timer->kernel_timer_id) == -1) { __timer_thread_stop(timer); return -1; } // Give the thread a meaningful name. // It can't do this itself because the kernel timer isn't created until after it's running. char name[32]; snprintf(name, sizeof(name), "POSIX interval timer %d", to_kernel_timer_id(timer)); pthread_setname_np(timer->callback_thread, name); *timer_id = timer; return 0; }
static int run(void) { int i, ret; printf("rxe_send_mc: starting %s\n", is_sender ? "client" : "server"); if (src_addr) { ret = get_addr(src_addr, (struct sockaddr *) &test.src_in); if (ret) return ret; } ret = get_addr(dst_addr, (struct sockaddr *) &test.dst_in); if (ret) return ret; printf("rxe_send_mc: joining\n"); for (i = 0; i < connections; i++) { if (src_addr) { ret = rdma_bind_addr(test.nodes[i].cma_id, test.src_addr); if (ret) { perror("rxe_send_mc: addr bind failure"); connect_error(); return ret; } } if (unmapped_addr) ret = addr_handler(&test.nodes[i]); else ret = rdma_resolve_addr(test.nodes[i].cma_id, test.src_addr, test.dst_addr, 2000); if (ret) { perror("rxe_send_mc: resolve addr failure"); connect_error(); return ret; } } ret = connect_events(); if (ret) goto out; pthread_create(&test.cmathread, NULL, cma_thread, NULL); /* * Pause to give SM chance to configure switches. We don't want to * handle reliability issue in this simple test program. */ sleep(3); if (message_batch) { if (is_sender) { printf("initiating data transfers\n"); for (i = 0; i < connections; i++) { ret = post_sends(&test.nodes[i], IBV_SEND_SIGNALED, 50); if (ret) goto out; } ret = poll_send_cqs(); } else { printf("receiving data transfers\n"); ret = poll_recv_cqs(); } if (ret) goto out; printf("data transfers complete\n"); } out: for (i = 0; i < connections; i++) { ret = rdma_leave_multicast(test.nodes[i].cma_id, test.dst_addr); if (ret) perror("rxe_send_mc: failure leaving"); } return ret; }
int main(int argc, char *argv[]) { char line,c; int i,j,e1, e2; edge e; createList(&edgeList, sizeof(edge), NULL); pthread_t thread_satcnf, thread_approx_1, thread_approx_2; loop:while(scanf(" %c", &line) != EOF) { switch(line) { case 'V': scanf(" %d", &numNodes); if(numNodes <= 0) { fprintf(stderr,"Error: Invalid number of vertices: %d!\n", numNodes); goto loop; } if(edgeList.length != 0) { destroy(&edgeList); } break; case 'E': scanf(" %c", &c); while(c != '}') { if(!scanf(" <%d,%d>", &e1,&e2)) goto loop; if( (e1 >= numNodes || e1 < 0) || (e2 >= numNodes || e2 < 0)) { fprintf(stderr,"Error: Invalid edge <%d,%d>!\n", e1, e2); destroy(&edgeList); goto loop; } e.p1 = e1; e.p2 = e2; append(&edgeList,&e); scanf("%c", &c); //scan ',' or '}' } thread_function_args thread_args[N]; /*initialize parameters for each thread function*/ for(i=0; i<N; i++) { thread_args[i].numNodes = numNodes; thread_args[i].edgeList = &edgeList; thread_args[i].vc = NULL; } int iter = 1; #ifdef DEBUG iter = 10; double ratio1,ratio2; double *runTimeSatCnf = (double *)malloc(iter*sizeof(double)); double *runTimeApprox1 = (double *)malloc(iter*sizeof(double)); double *runTimeApprox2 = (double *)malloc(iter*sizeof(double)); #endif for(j=0; j<iter; j++) { pthread_create(&thread_satcnf, NULL, &sat_cnf, &thread_args[0]); pthread_create(&thread_approx_1, NULL, &approx1, &thread_args[1]); pthread_create(&thread_approx_2, NULL, &approx2, &thread_args[2]); pthread_join(thread_satcnf, NULL); pthread_join(thread_approx_1, NULL); pthread_join(thread_approx_2, NULL); #ifdef DEBUG runTimeSatCnf[j] = thread_args[0].cputime; runTimeApprox1[j] = thread_args[1].cputime; runTimeApprox2[j] = thread_args[2].cputime; #endif } #ifdef DEBUG ratio1 = thread_args[1].vcSize / (double) thread_args[0].vcSize; ratio2 = thread_args[2].vcSize / (double) thread_args[0].vcSize; for(j=0; j<iter; j++) { //printf("%f,%f\n", runTimeApprox1[j],runTimeApprox2[j]); printf("%f,%f,%f\n", runTimeSatCnf[j],runTimeApprox1[j],runTimeApprox2[j]); fflush(stdout); } printf("%f,%f\n", ratio1,ratio2); printf("%f\n", ratio); fflush(stdout); for(i=0; i<N; i++) { free(thread_args[i].vc); } free(runTimeSatCnf); free(runTimeApprox1); free(runTimeApprox2); #else const char *name[N] = {"CNF-SAT-VC", "APPROX-VC-1", "APPROX-VC-2"}; for(i=0; i<N; i++) { printVC(thread_args[i].vcSize, thread_args[i].vc, name[i]); free(thread_args[i].vc); } #endif break; } } destroy(&edgeList); }
/*{{{ void ccsp_new_thread (void)*/ void ccsp_new_thread (void) { pthread_t thread; pthread_create (&thread, NULL, user_thread, NULL); }
static void add_to_output_plugins(hs_output_plugins *plugins, hs_output_plugin *p) { bool added = false; int idx = -1; pthread_mutex_lock(&plugins->list_lock); for (int i = 0; i < plugins->list_cap; ++i) { if (!plugins->list[i]) { idx = i; } else if (strcmp(plugins->list[i]->name, p->name) == 0) { idx = i; remove_plugin(plugins, idx); add_plugin(plugins, p, idx); added = true; break; } } if (!added && idx != -1) add_plugin(plugins, p, idx); if (idx == -1) { // todo probably don't want to grow it by 1 ++plugins->list_cap; hs_output_plugin **tmp = realloc(plugins->list, sizeof(hs_output_plugin *) * plugins->list_cap); idx = plugins->list_cap - 1; if (tmp) { plugins->list = tmp; add_plugin(plugins, p, idx); } else { hs_log(NULL, g_module, 0, "plugins realloc failed"); exit(EXIT_FAILURE); } } pthread_mutex_unlock(&plugins->list_lock); assert(p->list_index >= 0); hs_config *cfg = p->plugins->cfg; // sync the output and read checkpoints // the read and output checkpoints can differ to allow for batching hs_lookup_input_checkpoint(&cfg->cp_reader, hs_input_dir, p->name, cfg->output_path, &p->input.cp); p->cur.input.id = p->cp.input.id = p->input.cp.id; p->cur.input.offset = p->cp.input.offset = p->input.cp.offset; hs_lookup_input_checkpoint(&cfg->cp_reader, hs_analysis_dir, p->name, cfg->output_path, &p->analysis.cp); p->cur.analysis.id = p->cp.analysis.id = p->analysis.cp.id; p->cur.analysis.offset = p->cp.analysis.offset = p->analysis.cp.offset; int ret = pthread_create(&p->thread, NULL, input_thread, (void *)p); if (ret) { perror("pthread_create failed"); exit(EXIT_FAILURE); } }
int main () { std::ifstream ifile; ifile.open("inp-params.txt"); long long N; int ecount, dcount, l1, l2; while(!ifile.eof()) { ifile >> N >> ecount >> dcount >> l1 >> l2; } ifile.close(); LockBasedQueue * q = new LockBasedQueue (N); pthread_t enqueuer, dequeuer; //the threads struct ThreadMeta enqMeta, deqMeta; enqMeta.count = ecount; enqMeta.l = l1; enqMeta.q = q; deqMeta.count = dcount; deqMeta.l = l2; deqMeta.q = q; int check = pthread_create (&enqueuer, NULL, enqueue, (void*)&enqMeta); if (check) { std::cout << "Error in creating enqueuer" << std::endl; } int check2 = pthread_create (&dequeuer, NULL, dequeue, (void*)&deqMeta); if (check2) { std::cout << "Error in creating dequeuer" << std::endl; } pthread_join (enqueuer, NULL); pthread_join (dequeuer, NULL); std::ofstream ofile; ofile.open("output.txt"); for (std::vector<std::string>::iterator it = list.begin(); it != list.end(); ++it) { ofile << *it << std::endl; } delete q; ofile.close(); std::ofstream outfile; outfile.open("serial.txt"); while (enqlist.size() > 0 && deqlist.size() > 0) { if (enqlist[0].restime.count() < deqlist[0].invtime.count()) { outfile << enqlist[0].count + 1 << suffix(enqlist[0].count + 1) << " Enq("; if (enqlist[0].nilflag) { outfile << "nil"; }else { outfile << enqlist[0].val; } outfile << ").inv" << std::endl; outfile << enqlist[0].count + 1 << suffix(enqlist[0].count + 1) << " Enq("; if (enqlist[0].nilflag) { outfile << "nil"; } else { outfile << enqlist[0].val; } outfile << ").res" << std::endl; enqlist.erase(enqlist.begin()); } else if (deqlist[0].restime.count() < enqlist[0].invtime.count()) { outfile << deqlist[0].count + 1 << suffix(deqlist[0].count + 1) << " Deq("; if (deqlist[0].nilflag) { outfile << "nil"; } else { outfile << deqlist[0].val; } outfile << ").inv" << std::endl; outfile << deqlist[0].count + 1 << suffix(deqlist[0].count + 1) << " Deq("; if (deqlist[0].nilflag) { outfile << "nil"; } else { outfile << deqlist[0].val; } outfile << ").res" << std::endl; deqlist.erase(deqlist.begin()); } else { if (enqlist[0].val == deqlist[0].val) { outfile << enqlist[0].count + 1 << suffix(enqlist[0].count + 1) << " Enq("; if (enqlist[0].nilflag) { outfile << "nil"; }else { outfile << enqlist[0].val; } outfile << ").inv" << std::endl; outfile << enqlist[0].count + 1 << suffix(enqlist[0].count + 1) << " Enq("; if (enqlist[0].nilflag) { outfile << "nil"; } else { outfile << enqlist[0].val; } outfile << ").res" << std::endl; enqlist.erase(enqlist.begin()); outfile << deqlist[0].count + 1 << suffix(deqlist[0].count + 1) << " Deq("; if (deqlist[0].nilflag) { outfile << "nil"; } else { outfile << deqlist[0].val; } outfile << ").inv" << std::endl; outfile << deqlist[0].count + 1 << suffix(deqlist[0].count + 1) << " Deq("; if (deqlist[0].nilflag) { outfile << "nil"; } else { outfile << deqlist[0].val; } outfile << ").res" << std::endl; deqlist.erase(deqlist.begin()); } else { outfile << deqlist[0].count + 1 << suffix(deqlist[0].count + 1) << " Deq("; if (deqlist[0].nilflag) { outfile << "nil"; } else { outfile << deqlist[0].val; } outfile << ").inv" << std::endl; outfile << deqlist[0].count + 1 << suffix(deqlist[0].count + 1) << " Deq("; if (deqlist[0].nilflag) { outfile << "nil"; } else { outfile << deqlist[0].val; } outfile << ").res" << std::endl; deqlist.erase(deqlist.begin()); } } } if (enqlist.size() == 0) { while(deqlist.size() > 0) { outfile << deqlist[0].count + 1 << suffix(deqlist[0].count + 1) << " Deq("; if (deqlist[0].nilflag) { outfile << "nil"; } else { outfile << deqlist[0].val; } outfile << ").inv" << std::endl; outfile << deqlist[0].count + 1 << suffix(deqlist[0].count + 1) << " Deq("; if (deqlist[0].nilflag) { outfile << "nil"; } else { outfile << deqlist[0].val; } outfile << ").res" << std::endl; deqlist.erase(deqlist.begin()); } } if (deqlist.size() == 0) { while (enqlist.size() > 0) { outfile << enqlist[0].count + 1 << suffix(enqlist[0].count + 1) << " Enq("; if (enqlist[0].nilflag) { outfile << "nil"; }else { outfile << enqlist[0].val; } outfile << ").inv" << std::endl; outfile << enqlist[0].count + 1 << suffix(enqlist[0].count + 1) << " Enq("; if (enqlist[0].nilflag) { outfile << "nil"; } else { outfile << enqlist[0].val; } outfile << ").res" << std::endl; enqlist.erase(enqlist.begin()); } } outfile.close(); deqsum = deqsum / (dcount * 1.0); enqsum = enqsum / (ecount * 1.0); std::cout << "Average time to enqueue: " << enqsum << "useconds" << std::endl; std::cout << "Average time to dequeue: " << deqsum << "useconds" << std::endl; }
int sim_entry(struct ftm_param *param, void *priv) { bool exit = false; bool evdoDtSupport = false; int passCount = 0; struct sim_factory *sim = (struct sim_factory*)priv; struct itemview *iv = NULL; LOGD(TAG "%s: Start\n", __FUNCTION__); strcpy(sim->info, ""); init_text(&sim->title, param->name, COLOR_YELLOW); init_text(&sim->text, &sim->info[0], COLOR_YELLOW); if(NULL == sim->iv) { iv = ui_new_itemview(); if(!iv) { LOGD(TAG "No memory for item view"); return -1; } sim->iv = iv; } iv = sim->iv; iv->set_title(iv, &sim->title); iv->set_items(iv, sim_items, 0); iv->set_text(iv, &sim->text); iv->start_menu(iv,0); iv->redraw(iv); sim->exit_thread = false; #ifdef EVDO_DT_VIA_SUPPORT evdoDtSupport = true; #endif if(MTK_DT_SUPPORT && !evdoDtSupport) { snprintf(dev_node_1, 32, "%s", ccci_get_node_name(USR_FACTORY_SIM, MD_SYS1)); snprintf(dev_node_2, 32, "%s", ccci_get_node_name(USR_FACTORY_SIM, MD_SYS2)); pthread_create(&sim->update_thread, NULL, sim_update_thread_for_dualtalk, priv); } else { if (MTK_ENABLE_MD1) { snprintf(dev_node, 32, "%s", ccci_get_node_name(USR_FACTORY_SIM, MD_SYS1)); } else if (MTK_ENABLE_MD2) { snprintf(dev_node, 32, "%s", ccci_get_node_name(USR_FACTORY_SIM, MD_SYS2)); } else if (MTK_ENABLE_MD5){ snprintf(dev_node, 32, "%s", ccci_get_node_name(USR_FACTORY_SIM, MD_SYS5)); } else { LOGD("not open md1,md2,md5"); } pthread_create(&sim->update_thread, NULL, sim_update_thread, priv); } #if 0 while(!exit) { int chosen = iv->run(iv, &exit); switch(chosen) { case ITEM_SIM1: sim->sim_id = SIM_ID_1; sim->test_done = false; exit = false; break; case ITEM_SIM2: sim->sim_id = SIM_ID_2; sim->test_done = false; exit = false; break; case ITEM_PASS: case ITEM_FAIL: if(ITEM_PASS == chosen) { sim->mod->test_result = FTM_TEST_PASS; } else { sim->mod->test_result = FTM_TEST_FAIL; } sim->exit_thread = true; sim->test_done = true; exit = true; break; default: sim->exit_thread = true; sim->test_done = true; exit = true; LOGD(TAG "DEFAULT EXIT\n"); break; } // end switch(chosen) if(exit) { sim->exit_thread = true; } } // end while(!exit) #endif //Detect SIM 1 // strcpy(sim->info, ""); memset(sim->info, 0, sizeof(sim->info) / sizeof(*(sim->info))); sim->sim_id = SIM_ID_1; sim->test_done = false; while (strlen(sim->info) == 0) { LOGD (TAG "detect slot 1:enter"); LOGD (TAG "sim_entry:sim->info:%s, lenth:%d",sim->info,strlen(sim->info)); usleep(200000); if (strstr(sim->info, uistr_info_pass)) { passCount++; } } LOGD(TAG "[SLOT 1]passCount = %d\n", passCount); LOGD (TAG "begin redraw"); iv->redraw(iv); LOGD (TAG "end redraw"); #if defined(GEMINI) || defined(MTK_GEMINI_3SIM_SUPPORT)|| defined(EVDO_DT_VIA_SUPPORT) || defined(FTM_SIM_USE_USIMSMT) //Detect SIM 2 // strcpy(sim->info, ""); memset(sim->info, 0, sizeof(sim->info) / sizeof(*(sim->info))); sim->sim_id = SIM_ID_2; sim->test_done = false; while (strlen(sim->info) == 0) { LOGD (TAG "detect slot 2:enter"); LOGD (TAG "sim_entry:sim->info:%s, lenth:%d",sim->info,strlen(sim->info)); usleep(200000); if (strstr(sim->info, uistr_info_pass)) { passCount++; } } LOGD(TAG "[SLOT 2]passCount = %d\n", passCount); LOGD (TAG "begin redraw"); iv->redraw(iv); LOGD (TAG "end redraw"); #else passCount++; LOGD(TAG "GEMINI is not defined, do not need to check SIM2\n"); #endif #if defined(MTK_GEMINI_3SIM_SUPPORT) //Detect SIM 3 // strcpy(sim->info, ""); memset(sim->info, 0, sizeof(sim->info) / sizeof(*(sim->info))); sim->sim_id = SIM_ID_3; sim->test_done = false; while (strlen(sim->info) == 0) { LOGD (TAG "detect slot 3:enter"); LOGD (TAG "sim_entry:sim->info:%s, lenth:%d",sim->info,strlen(sim->info)); usleep(200000); if (strstr(sim->info, uistr_info_pass)) { passCount++; } } LOGD(TAG "[SLOT 3]passCount = %d\n", passCount); LOGD (TAG "begin redraw"); iv->redraw(iv); LOGD (TAG "end redraw"); #else passCount++; LOGD(TAG "MTK_GEMINI_3SIM_SUPPORT is not defined, do not need to check SIM3\n"); #endif //Exit SIM detect thread sim->exit_thread = true; sim->test_done = true; pthread_join(sim->update_thread, NULL); //Check test result if (passCount == 3) { //SIM1, SIM2 and SIM3 are detected. sim->mod->test_result = FTM_TEST_PASS; } else { sim->mod->test_result = FTM_TEST_FAIL; } LOGD(TAG "%s: End\n", __FUNCTION__); return 0; }
int mono_gc_pthread_create (pthread_t *new_thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg) { return pthread_create (new_thread, attr, start_routine, arg); }
int main(int argc, char *argv[]) { if (argc != 5) { printf("You should input five arguments: TCP/UDP, server ip address, buffer size and number of threads.\n"); return(1); } //Get parameters from the input. char *server_ip = argv[2]; int buffer_size = atoi(argv[3]); int num_thr = atoi(argv[4]); if (buffer_size == 65536) { buffer_size = 65507; } //Define and initialize the socket related parameters. struct sockaddr_in server_addr; server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr(server_ip); server_addr.sin_port = htons(4567); //Initializing threads and assign related parameters. struct thread_arg *thr_arg = (struct thread_arg *)malloc(sizeof(struct thread_arg)); thr_arg -> server_addr = server_addr; thr_arg -> buf_size = buffer_size; pthread_t threads[num_thr]; //Define the start time and end time. int i = 0; struct timeval start_time, end_time; //Start executing communication using multi-threads, get the start time and end time. gettimeofday(&start_time, NULL); if (strcmp(argv[1], "TCP") == 0) { for (i = 0; i < num_thr; ++i) { pthread_create(&threads[i], NULL, tcpClient, thr_arg); } for (i = 0; i < num_thr; ++i) { pthread_join(threads[i], NULL); } } else { for (i = 0; i < num_thr; ++i) { pthread_create(&threads[i], NULL, udpClient, thr_arg); } for (i = 0; i < num_thr; ++i) { pthread_join(threads[i], NULL); } } gettimeofday(&end_time, NULL); //Calculate the execte time and throughput. double execute_time = (1000.0 * (end_time.tv_sec - start_time.tv_sec) + (end_time.tv_usec - start_time.tv_usec) / 1000.0); double throughput = (num_thr * LOOPS * buffer_size / (1024.0 * 1024.0)) / (execute_time / 1000.0); double latency = execute_time / (num_thr * LOOPS * buffer_size); printf("%d threads: the latency is %10.9f ms and the throughput is %10f MB/S\n", num_thr, latency, throughput); return 0; }