本文整理汇总了C++中pthread_join函数的典型用法代码示例。如果您正苦于以下问题:C++ pthread_join函数的具体用法?C++ pthread_join怎么用?C++ pthread_join使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了pthread_join函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。
示例1: chitcpd_server_thread_func
//.........这里部分代码省略.........
ha->si = si;
handler_thread = malloc(sizeof(handler_thread_t));
handler_thread->handler_socket = client_socket;
pthread_mutex_init(&handler_thread->handler_lock, NULL);
/* Create handler thread to handle this connection */
ha->client_socket = handler_thread->handler_socket;
ha->handler_lock = &handler_thread->handler_lock;
snprintf(ha->thread_name, 16, "handler-%d", next_thread_id++);
if (pthread_create(&handler_thread->thread, NULL, chitcpd_handler_dispatch, ha) != 0)
{
perror("Could not create a worker thread");
resp_outer.resp->ret = CHITCP_ETHREAD;
resp_outer.resp->error_code = 0;
rc = chitcpd_send_msg(client_socket, &resp_outer);
free(ha);
close(ha->client_socket);
close(si->server_socket);
// TODO: Perform an orderly shutdown instead of exiting
pthread_exit(NULL);
}
resp_outer.resp->ret = CHITCP_OK;
resp_outer.resp->error_code = 0;
rc = chitcpd_send_msg(client_socket, &resp_outer);
list_append(&handler_thread_list, handler_thread);
}
else if(conntype == CHITCPD_CONNECTION_TYPE__DEBUG_CONNECTION)
{
int debug_sockfd, debug_event_flags;
ChitcpdDebugArgs *debug_args;
/* Unpack debug parameter */
assert(init_args->debug != NULL);
debug_args = init_args->debug;
debug_sockfd = debug_args->sockfd;
debug_event_flags = debug_args->event_flags;
rc = chitcpd_init_debug_connection(si, debug_sockfd, debug_event_flags, client_socket);
if(rc == CHITCP_OK)
{
resp_outer.resp->ret = CHITCP_OK;
resp_outer.resp->error_code = 0;
rc = chitcpd_send_msg(client_socket, &resp_outer);
}
else
{
chilog(ERROR, "Error when creating debug connection for socket %i", debug_sockfd);
resp_outer.resp->ret = CHITCP_EINIT;
resp_outer.resp->error_code = rc;
rc = chitcpd_send_msg(client_socket, &resp_outer);
shutdown(client_socket, SHUT_RDWR);
}
}
else
{
chilog(ERROR, "Received INIT message with unknown connection type %i", conntype);
resp_outer.resp->ret = CHITCP_EINVAL;
resp_outer.resp->error_code = 0;
rc = chitcpd_send_msg(client_socket, &resp_outer);
shutdown(client_socket, SHUT_RDWR);
}
chitcpd_msg__free_unpacked(req, NULL);
}
while(!list_empty(&handler_thread_list))
{
/* For each handler thread we spawned, we close its socket, which
* will force the thread to exit (and we then join it).
*
* Note that closing a handler thread will also free up all chiTCP
* sockets created through that thread, and will also terminate
* all associated TCP threads.
*
* TODO: We should simply detach those threads, since they can exit
* before an orderly shutdown and would be left lingering until
* we call join here. */
handler_thread_t *ht = list_fetch(&handler_thread_list);
/* We don't want to shutdown the handler's socket if an operation is
* in progress. The handler thread may have read a command, but
* not sent a response back yet */
pthread_mutex_lock(&ht->handler_lock);
shutdown(ht->handler_socket, SHUT_RDWR);
pthread_mutex_unlock(&ht->handler_lock);
pthread_join(ht->thread, NULL);
pthread_mutex_destroy(&ht->handler_lock);
free(ht);
}
list_destroy(&handler_thread_list);
pthread_exit(NULL);
}
开发者ID:gokul-uf,项目名称:chitcp,代码行数:101,代码来源:server.c
示例2: TEST
// This test is disable because it is for generating test data.
TEST(libbacktrace, DISABLED_generate_offline_testdata) {
// Create a thread to generate the needed stack and registers information.
const size_t stack_size = 16 * 1024;
void* stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
ASSERT_NE(MAP_FAILED, stack);
uintptr_t stack_addr = reinterpret_cast<uintptr_t>(stack);
pthread_attr_t attr;
ASSERT_EQ(0, pthread_attr_init(&attr));
ASSERT_EQ(0, pthread_attr_setstack(&attr, reinterpret_cast<void*>(stack), stack_size));
pthread_t thread;
OfflineThreadArg arg;
arg.exit_flag = 0;
ASSERT_EQ(0, pthread_create(&thread, &attr, OfflineThreadFunc, &arg));
// Wait for the offline thread to generate the stack and unw_context information.
sleep(1);
// Copy the stack information.
std::vector<uint8_t> stack_data(reinterpret_cast<uint8_t*>(stack),
reinterpret_cast<uint8_t*>(stack) + stack_size);
arg.exit_flag = 1;
ASSERT_EQ(0, pthread_join(thread, nullptr));
ASSERT_EQ(0, munmap(stack, stack_size));
std::unique_ptr<BacktraceMap> map(BacktraceMap::Create(getpid()));
ASSERT_TRUE(map != nullptr);
backtrace_stackinfo_t stack_info;
stack_info.start = stack_addr;
stack_info.end = stack_addr + stack_size;
stack_info.data = stack_data.data();
// Generate offline testdata.
std::string testdata;
// 1. Dump pid, tid
testdata += android::base::StringPrintf("pid: %d tid: %d\n", getpid(), arg.tid);
// 2. Dump maps
for (auto it = map->begin(); it != map->end(); ++it) {
testdata += android::base::StringPrintf(
"map: start: %" PRIxPTR " end: %" PRIxPTR " offset: %" PRIxPTR " load_bias: %" PRIxPTR
" flags: %d name: %s\n",
it->start, it->end, it->offset, it->load_bias, it->flags, it->name.c_str());
}
// 3. Dump registers
testdata += android::base::StringPrintf("registers: %zu ", sizeof(arg.unw_context));
testdata += RawDataToHexString(&arg.unw_context, sizeof(arg.unw_context));
testdata.push_back('\n');
// 4. Dump stack
testdata += android::base::StringPrintf(
"stack: start: %" PRIx64 " end: %" PRIx64 " size: %zu ",
stack_info.start, stack_info.end, stack_data.size());
testdata += RawDataToHexString(stack_data.data(), stack_data.size());
testdata.push_back('\n');
// 5. Dump function symbols
std::vector<FunctionSymbol> function_symbols = GetFunctionSymbols();
for (const auto& symbol : function_symbols) {
testdata += android::base::StringPrintf(
"function: start: %" PRIxPTR " end: %" PRIxPTR" name: %s\n",
symbol.start, symbol.end, symbol.name.c_str());
}
ASSERT_TRUE(android::base::WriteStringToFile(testdata, "offline_testdata"));
}
开发者ID:vicamo,项目名称:b2g_platform_system_core,代码行数:64,代码来源:backtrace_offline_test.cpp
示例3: main
//.........这里部分代码省略.........
rv = poll(pollfd, polli, 10);
if (rv <= 0) {
if (rv < 0 && errno != EAGAIN && errno != EINTR)
RD(1, "poll error %s", strerror(errno));
continue;
}
if (oq) {
/* try to push packets from the overflow queues
* to the corresponding pipes
*/
for (i = 0; i < npipes; i++) {
struct port_des *p = &ports[i];
struct overflow_queue *q = p->oq;
struct group_des *g = p->group;
uint32_t j, lim;
struct netmap_ring *ring;
struct netmap_slot *slot;
if (oq_empty(q))
continue;
ring = p->ring;
lim = nm_ring_space(ring);
if (!lim)
continue;
if (q->n < lim)
lim = q->n;
for (j = 0; j < lim; j++) {
struct netmap_slot s = oq_deq(q), tmp;
tmp.ptr = 0;
slot = &ring->slot[ring->cur];
if (slot->ptr && !g->last) {
tmp.buf_idx = forward_packet(g + 1, slot);
/* the forwarding may have removed packets
* from the current queue
*/
if (q->n < lim)
lim = q->n;
} else {
tmp.buf_idx = slot->buf_idx;
}
oq_enq(freeq, &tmp);
*slot = s;
slot->flags |= NS_BUF_CHANGED;
ring->cur = nm_ring_next(ring, ring->cur);
}
ring->head = ring->cur;
forwarded += lim;
p->ctr.pkts += lim;
}
}
int batch = 0;
for (i = rxport->nmd->first_rx_ring; i <= rxport->nmd->last_rx_ring; i++) {
struct netmap_ring *rxring = NETMAP_RXRING(rxport->nmd->nifp, i);
//D("prepare to scan rings");
int next_cur = rxring->cur;
struct netmap_slot *next_slot = &rxring->slot[next_cur];
const char *next_buf = NETMAP_BUF(rxring, next_slot->buf_idx);
while (!nm_ring_empty(rxring)) {
struct netmap_slot *rs = next_slot;
struct group_des *g = &groups[0];
// CHOOSE THE CORRECT OUTPUT PIPE
uint32_t hash = pkt_hdr_hash((const unsigned char *)next_buf, 4, 'B');
if (hash == 0) {
non_ip++; // XXX ??
}
rs->ptr = hash | (1UL << 32);
// prefetch the buffer for the next round
next_cur = nm_ring_next(rxring, next_cur);
next_slot = &rxring->slot[next_cur];
next_buf = NETMAP_BUF(rxring, next_slot->buf_idx);
__builtin_prefetch(next_buf);
// 'B' is just a hashing seed
rs->buf_idx = forward_packet(g, rs);
rs->flags |= NS_BUF_CHANGED;
rxring->head = rxring->cur = next_cur;
batch++;
if (unlikely(batch >= glob_arg.batch)) {
ioctl(rxport->nmd->fd, NIOCRXSYNC, NULL);
batch = 0;
}
ND(1,
"Forwarded Packets: %"PRIu64" Dropped packets: %"PRIu64" Percent: %.2f",
forwarded, dropped,
((float)dropped / (float)forwarded * 100));
}
}
}
pthread_join(stat_thread, NULL);
printf("%"PRIu64" packets forwarded. %"PRIu64" packets dropped. Total %"PRIu64"\n", forwarded,
dropped, forwarded + dropped);
return 0;
}
开发者ID:intersvyaz,项目名称:netmap,代码行数:101,代码来源:lb.c
示例4: main
int
main()
{
int failed = 0;
int i;
int first, last;
pthread_t t[NUMTHREADS + 1];
assert((t[0] = pthread_self()).p != NULL);
assert(cvthing.notbusy == PTHREAD_COND_INITIALIZER);
assert(cvthing.lock == PTHREAD_MUTEX_INITIALIZER);
(void) pthread_win32_getabstime_np(&abstime, &reltime);
assert((t[0] = pthread_self()).p != NULL);
awoken = 0;
for (first = 1, last = NUMTHREADS / 2;
first < NUMTHREADS;
first = last + 1, last = NUMTHREADS)
{
assert(pthread_mutex_lock(&start_flag) == 0);
for (i = first; i <= last; i++)
{
threadbag[i].started = 0;
threadbag[i].threadnum = i;
assert(pthread_create(&t[i], NULL, mythread, (void *) &threadbag[i]) == 0);
}
/*
* Code to control or manipulate child threads should probably go here.
*/
cvthing.shared = 0;
assert(pthread_mutex_unlock(&start_flag) == 0);
/*
* Give threads time to start.
*/
Sleep(100);
assert(pthread_mutex_lock(&cvthing.lock) == 0);
cvthing.shared++;
assert(pthread_mutex_unlock(&cvthing.lock) == 0);
assert(pthread_cond_broadcast(&cvthing.notbusy) == 0);
/*
* Give threads time to complete.
*/
for (i = first; i <= last; i++)
{
assert(pthread_join(t[i], NULL) == 0);
}
assert(awoken == (i - 1));
}
/*
* Standard check that all threads started.
*/
for (i = 1; i <= NUMTHREADS; i++)
{
failed = !threadbag[i].started;
if (failed)
{
fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started);
}
}
/*
* Cleanup the CV.
*/
assert(pthread_mutex_destroy(&cvthing.lock) == 0);
assert(cvthing.lock == NULL);
assert(pthread_cond_destroy(&cvthing.notbusy) == 0);
assert(cvthing.notbusy == NULL);
assert(!failed);
/*
* Check any results here.
*/
assert(awoken == NUMTHREADS);
/*
* Success.
*/
return 0;
//.........这里部分代码省略.........
开发者ID:pps83,项目名称:pthread-win32,代码行数:101,代码来源:condvar8.c
示例5: function
/*
MSVM2 training function (Frank-Wolfe algorithm)
Solves the dual problem wrt alpha:
min 1/2 alpha' H_tilde alpha - (1/Q-1) sum (alpha)
s.t.
alpha_ik >= 0, for all i,k, such that 1 <= i <= m, 1 <= k != y_i <= Q
sum_i (alpha_ik - average_alpha_k) = 0, for all k, 1 <= k <= Q
where
H_tilde_ik,jl = (delta_k,l - 1/Q) ( k(x_i,x_j) + (1/2C)delta_i,j )
*/
long MSVM_2fw_train(struct Model *model, struct Data *training_set, long chunk_size, const double accuracy, int cache_memory, const int nprocs, char *alpha0_file, char *model_tmp_file, char *log_file)
{
long return_status = -1;
FILE *fp;
int t;
pthread_t *threads = (pthread_t *)malloc(sizeof(pthread_t) * nprocs); // threads id
void *status; // for pthread_join
int rc; // return code of pthread functions
pthread_t thread_monitor;
enum AlphaInitType alphaiszero;
if(training_set != NULL) {
// Initialize model for this particular training set
model_load_data(model, training_set);
}
if(model->nb_data > 2147483647) {
printf("Cannot compute table chunk: number of data above random number limit\n");
exit(0);
}
// Check if a kernel_par has been set
if(model->nature_kernel != LINEAR && model->kernel_par == NULL)
set_default_kernel_par(model);
// Log file
if (log_file != NULL) {
printf("\nLog training info in %s ...\n", log_file);
fp = fopen(log_file,"a");
}
else
fp = NULL;
// Initialize alpha and b
if(training_set != NULL) // otherwise resume training
init_alpha_b(model, alpha0_file); // use init_alpha_b(model, NULL); to initialize all alpha to 0
if(training_set == NULL || alpha0_file != NULL)
alphaiszero = ALPHA_NOT_ZERO;
else
alphaiszero = ALPHA_IS_ZERO;
EVAL = 0; // triggered by signal handler to call eval
STOP = 0; // triggered by user to stop training
// Prepare monitoring of model
struct MonitorData monitor_data;
monitor_data.model_tmp_file = model_tmp_file;
monitor_data.period = MONITOR_PERIOD;
monitor_data.model = model;
pthread_create(&thread_monitor, NULL, MSVM_monitor_model_thread, (void *) &monitor_data);
// Allocate memory for shared ressources
double **gradient = matrix(model->nb_data, model->Q);
double **H_alpha = matrix(model->nb_data, model->Q);
double **H_tilde_alpha = matrix(model->nb_data, model->Q);
double best_primal_upper_bound = HUGE_VAL;
int *activeset = (int *)calloc(model->nb_data+1, sizeof(int));
double *lp_rhs = (double*)calloc(model->Q, sizeof(double));
// including the kernel cache:
struct KernelCache kc;
unsigned long cache_size = (unsigned long)cache_memory * MBYTES;
kernel_initialize_cache(cache_size, &kc, model);
printf("Initialization... ");fflush(stdout);
// Initialize gradient
MSVM2fw_init_gradient(alphaiszero, gradient, H_alpha,H_tilde_alpha, model);
printf("Done.\n");
// Initialize display
if(accuracy>0)
print_training_info(0,model);
else {
printf("Training...");fflush(stdout);
}
model->iter = 1; // number of iterations (over all threads)
// Prepare data for computing threads
//.........这里部分代码省略.........
开发者ID:WittyElephant,项目名称:ML_SVM_Ridge_Regression,代码行数:101,代码来源:libtrainMSVM_2fw.c
示例6: aguardarTerminoDeThreads
void aguardarTerminoDeThreads(pthread_t thread[]){
int i;
for(i = 0; i < NTHREADS; i++){
pthread_join(thread[i], NULL);
}
}
开发者ID:paladini,项目名称:UFSC-concurrent-programming,代码行数:6,代码来源:trabalho1Emma.c
示例7: main
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);
//.........这里部分代码省略.........
开发者ID:chrisplyn,项目名称:ece650,代码行数:101,代码来源:main.c
示例8: input_thread
//.........这里部分代码省略.........
}
#endif
}
// if we have one send the oldest first
if (pim) {
if (pam) {
if (pim->timestamp <= pam->timestamp) {
msg = pim;
} else {
msg = pam;
}
} else {
msg = pim;
}
} else if (pam) {
msg = pam;
}
if (msg) {
if (msg == pim) {
pim = NULL;
p->cur.input.id = p->input.cp.id;
p->cur.input.offset = p->input.cp.offset -
(p->input.ib.readpos - p->input.ib.scanpos);
} else {
pam = NULL;
p->cur.analysis.id = p->analysis.cp.id;
p->cur.analysis.offset = p->analysis.cp.offset -
(p->analysis.ib.readpos - p->analysis.ib.scanpos);
}
ret = output_message(p, msg);
if (ret == LSB_HEKA_PM_RETRY) {
while (!p->stop && ret == LSB_HEKA_PM_RETRY) {
const char *err = lsb_heka_get_error(p->hsb);
hs_log(NULL, p->name, 7, "retry message %llu err: %s", p->sequence_id,
err);
sleep(1);
ret = output_message(p, msg);
}
}
if (ret > 0) {
break; // fatal error
}
msg = NULL;
} else if (!bytes_read[0] && !bytes_read[1]) {
// trigger any pending timer events
lsb_clear_heka_message(&im); // create an idle/empty message
msg = &im;
output_message(p, msg);
msg = NULL;
sleep(1);
}
}
shutdown_timer_event(p);
lsb_free_heka_message(&am);
lsb_free_heka_message(&im);
// hold the current checkpoints in memory incase we restart it
hs_update_input_checkpoint(&p->plugins->cfg->cp_reader,
hs_input_dir,
p->name,
&p->cp.input);
hs_update_input_checkpoint(&p->plugins->cfg->cp_reader,
hs_analysis_dir,
p->name,
&p->cp.analysis);
if (p->stop) {
hs_log(NULL, p->name, 6, "shutting down");
} else {
hs_log(NULL, p->name, 6, "detaching received: %d msg: %s", ret,
lsb_heka_get_error(p->hsb));
pthread_mutex_lock(&p->plugins->list_lock);
hs_output_plugins *plugins = p->plugins;
plugins->list[p->list_index] = NULL;
if (pthread_detach(p->thread)) {
hs_log(NULL, p->name, 3, "thread could not be detached");
}
destroy_output_plugin(p);
--plugins->list_cnt;
pthread_mutex_unlock(&plugins->list_lock);
}
pthread_exit(NULL);
}
static void remove_plugin(hs_output_plugins *plugins, int idx)
{
hs_output_plugin *p = plugins->list[idx];
plugins->list[idx] = NULL;
p->stop = true;
if (pthread_join(p->thread, NULL)) {
hs_log(NULL, p->name, 3, "remove_plugin could not pthread_join");
}
destroy_output_plugin(p);
--plugins->list_cnt;
}
开发者ID:dbaba,项目名称:hindsight,代码行数:101,代码来源:hs_output_plugins.c
示例9: CreateThread
//.........这里部分代码省略.........
#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
开发者ID:Edimartin,项目名称:edk-source,代码行数:67,代码来源:Thread.cpp
示例10: main
//.........这里部分代码省略.........
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;
}
开发者ID:reklaklislaw,项目名称:metadata2ontology,代码行数:101,代码来源:findfield.c
示例11: join
void join(){
if(!s) run();
pthread_join(thr, 0);
s = 0;
}
开发者ID:TheHandsomeCoder,项目名称:mkn.kul,代码行数:5,代码来源:threads.os.hpp
示例12: sock_ep_close
static int sock_ep_close(struct fid *fid)
{
struct sock_ep *sock_ep;
char c = 0;
switch(fid->fclass) {
case FI_CLASS_EP:
sock_ep = container_of(fid, struct sock_ep, ep.fid);
break;
case FI_CLASS_SEP:
sock_ep = container_of(fid, struct sock_ep, ep.fid);
break;
default:
return -FI_EINVAL;
}
if (atomic_get(&sock_ep->ref) || atomic_get(&sock_ep->num_rx_ctx) ||
atomic_get(&sock_ep->num_tx_ctx))
return -FI_EBUSY;
if (sock_ep->fclass != FI_CLASS_SEP && !sock_ep->tx_shared) {
sock_pe_remove_tx_ctx(sock_ep->tx_array[0]);
sock_tx_ctx_free(sock_ep->tx_array[0]);
}
if (sock_ep->fclass != FI_CLASS_SEP && !sock_ep->rx_shared) {
sock_pe_remove_rx_ctx(sock_ep->rx_array[0]);
sock_rx_ctx_free(sock_ep->rx_array[0]);
}
free(sock_ep->tx_array);
free(sock_ep->rx_array);
if (sock_ep->src_addr)
free(sock_ep->src_addr);
if (sock_ep->dest_addr)
free(sock_ep->dest_addr);
if (sock_ep->ep_type == FI_EP_MSG) {
sock_ep->cm.do_listen = 0;
if (write(sock_ep->cm.signal_fds[0], &c, 1) != 1) {
SOCK_LOG_INFO("Failed to signal\n");
}
if (sock_ep->cm.listener_thread &&
pthread_join(sock_ep->cm.listener_thread, NULL)) {
SOCK_LOG_ERROR("pthread join failed (%d)\n", errno);
}
close(sock_ep->cm.signal_fds[0]);
close(sock_ep->cm.signal_fds[1]);
}
sock_ep->listener.do_listen = 0;
if (write(sock_ep->listener.signal_fds[0], &c, 1) != 1) {
SOCK_LOG_INFO("Failed to signal\n");
}
if (pthread_join(sock_ep->listener.listener_thread, NULL)) {
SOCK_LOG_ERROR("pthread join failed (%d)\n", errno);
}
close(sock_ep->listener.signal_fds[0]);
close(sock_ep->listener.signal_fds[1]);
sock_fabric_remove_service(sock_ep->domain->fab,
atoi(sock_ep->listener.service));
atomic_dec(&sock_ep->domain->ref);
free(sock_ep);
return 0;
}
开发者ID:nkogteva,项目名称:ompi,代码行数:75,代码来源:sock_ep.c
示例13: main
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);
}
开发者ID:Manfrins,项目名称:CsInfoPa,代码行数:63,代码来源:bis1.c
示例14: daemon_start
/*
* Daemonize and persist pid
*/
int
daemon_start()
{
struct sigaction sig_action;
sigset_t sig_set;
pid_t otherpid;
int curPID;
pthread_t tcp4_thread, udp4_thread;
pthread_t tcp6_thread, udp6_thread;
/* Check if we can acquire the pid file */
pfh = pidfile_open(NULL, 0644, &otherpid);
if (pfh == NULL) {
if (errno == EEXIST) {
errx(EXIT_FAILURE, "Daemon already running, pid: %jd.", (intmax_t)otherpid);
}
err(EXIT_FAILURE, "Cannot open or create pidfile");
}
init_logger();
/* Initialize TCP46 and UDP46 sockets */
if (init_tcp() == EXIT_FAILURE)
return (EXIT_FAILURE);
if (init_udp() == EXIT_FAILURE)
return (EXIT_FAILURE);
/* start daemonizing */
curPID = fork();
switch (curPID) {
case 0: /* This process is the child */
break;
case -1: /* fork() failed, should exit */
perror("fork");
return (EXIT_FAILURE);
default: /* fork() successful, should exit
* (parent) */
return (EXIT_SUCCESS);
}
/* we are the child, complete the daemonization */
/* Close standard IO */
fclose(stdin);
fclose(stdout);
fclose(stderr);
/* Block unnecessary signals */
sigemptyset(&sig_set);
sigaddset(&sig_set, SIGCHLD); /* ignore child - i.e. we don't need
* to wait for it */
sigaddset(&sig_set, SIGTSTP); /* ignore tty stop signals */
sigaddset(&sig_set, SIGTTOU); /* ignore tty background writes */
sigaddset(&sig_set, SIGTTIN); /* ignore tty background reads */
sigprocmask(SIG_BLOCK, &sig_set, NULL); /* Block the above specified
* signals */
/* Catch necessary signals */
sig_action.sa_handler = signal_handler;
sigemptyset(&sig_action.sa_mask);
sig_action.sa_flags = 0;
sigaction(SIGTERM, &sig_action, NULL);
sigaction(SIGHUP, &sig_action, NULL);
sigaction(SIGINT, &sig_action, NULL);
/* create new session and process group */
setsid();
/* persist pid */
pidfile_write(pfh);
/* Create TCP and UDP listener threads */
pthread_create(&tcp4_thread, NULL, tcp4_handler, NULL);
pthread_create(&udp4_thread, NULL, udp4_handler, NULL);
#ifdef PF_INET6
pthread_create(&tcp6_thread, NULL, tcp6_handler, NULL);
pthread_create(&udp6_thread, NULL, udp6_handler, NULL);
#endif
/*
* Wait for threads to terminate, which normally shouldn't ever
* happen
*/
pthread_join(tcp4_thread, NULL);
pthread_join(udp4_thread, NULL);
#ifdef PF_INET6
pthread_join(tcp6_thread, NULL);
pthread_join(udp6_thread, NULL);
#endif
return (EXIT_SUCCESS);
}
开发者ID:farrokhi,项目名称:fsipd,代码行数:97,代码来源:fsipd.c
示例15: sim_entry
//.........这里部分代码省略.........
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;
}
开发者ID:WayWingsDev,项目名称:mediatek,代码行数:101,代码来源:ftm_sim.c
示例16: pthread_mutex_unlock
//.........这里部分代码省略.........
select_random_chunk(&cache,model);
// Compute the kernel submatrix for this chunk
compute_K(&cache,model);
// Enter Critical Section (using and modifying the model)
pthread_mutex_lock(&(model->mutex));
jump = MSVM2fw_solve_lp(gradient, &cache, model);
if(jump == false)
jump = MSVM2fw_check_opt_sol(gradient,&cache,model);
if(jump == false) {
MSVM2fw_compute_delta(delta,&cache,model);
theta_opt = MSVM2fw_compute_theta_opt(delta, &cache, model);
*nb_SV += MSVM2fw_compute_new_alpha(theta_opt,&cache,model);
if(parallel_gradient_update && numthreads_grad > 1) {
// Update gradient in parallel
for(k=0;k<numthreads_grad;k++) {
#ifdef _WIN32
SubmitThreadpoolWork(work[k]);
#else
rc = pthread_create(&grad_threads[k], NULL, MSVM2fw_update_gradient_thread, (void *) &grad_data[k]);
#endif
}
// Wait for gradient computations to terminate
for(k=0;k<numthreads_grad;k++) {
#ifdef _WIN32
WaitForThreadpoolWorkCallbacks(work[k], FALSE);
#else
rc = pthread_join(grad_threads[k],&status);
#endif
}
}
else {
// old-style non-threaded gradient update (for small data sets)
MSVM2fw_update_gradient(gradient,H_alpha, H_tilde_alpha, &cache,model);
}
}
if((do_eval && (model->iter%TRAIN_STEP) == 0) || EVAL || STOP || (do_eval && model->ratio >= accuracy) )
{
if(fp != NULL)
fprintf(fp,"%ld ",model->iter);
if(EVAL)
printf("\n\n*** Evaluating the model at iteration %ld...\n",model->iter);
// Evaluate how far we are in the optimization
// (prints more info if interrutped by user)
model->ratio = MSVM_eval(best_primal_upper_bound, gradient, H_alpha, H_tilde_alpha, model, EVAL, fp);
print_training_info(*nb_SV, model);
if(EVAL) // if interrupted by user (otherwise let the ratio decide if we go on training)
{
printf("\n *** Do you want to continue training ([y]/n)? ");
yesno = getchar();
if(yesno=='n') {
STOP = 1;
}
开发者ID:WittyElephant,项目名称:ML_SVM_Ridge_Regression,代码行数:67,代码来源:libtrainMSVM_2fw.c
示例17: main
//.........这里部分代码省略.........
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.
|
请发表评论