int main(int argc, char *argv[]) { int s, s1; // Socket descriptors init_logger(); init_thread_info(); configuration_load(argc,argv); if (weborf_conf.is_inetd) inetd(); print_start_disclaimer(argc,argv); s=net_create_server_socket(); net_bind_and_listen(s); set_new_gid(weborf_conf.gid); set_new_uid(weborf_conf.uid); // init the queue for opened sockets if (q_init(&queue, MAXTHREAD + 1)!=0) exit(NOMEM); // Starts the 1st group of threads init_thread_attr(); init_threads(INITIALTHREAD); init_thread_shaping(); init_signals(); // Infinite cycle, accept connections while (1) { s1=accept(s, NULL,NULL); if (s1 >= 0 && q_put(&queue, s1)!=0) { // Adds s1 to the queue #ifdef REQUESTDBG syslog(LOG_ERR,"Not enough resources, dropping connection..."); #endif close(s1); } // Start new thread if needed if (thread_info.free <= LOWTHREAD && thread_info.free<MAXTHREAD) { // Need to start new thread if (thread_info.count + INITIALTHREAD < MAXTHREAD) { // Starts a group of threads init_threads(INITIALTHREAD); } else { // Can't start a group because the limit is close, starting less than a whole group init_threads(MAXTHREAD - thread_info.count); } } } return 0; }
int main(int argc, char *argv[]) { init_sockets(); init_threads(); int listen_port = 7; if(argc == 2) { listen_port = atoi(argv[1]); } else { printf("usage: %s [local_port (default: %d)]\n", argv[0], listen_port); } printf("running server on port %d\n", listen_port); client_listen_fd = get_listen_fd(listen_port); for(;;) { int client_fd = accept(client_listen_fd, NULL, NULL); new_thread((void*)handle_connection, client_fd); } }
void start_simulation(void) { int kernel_st ; int tmp ; { { kernel_st = 0; init_threads(); } { while (1) { while_3_continue: /* CIL Label */ ; { kernel_st = 1; eval(); tmp = stop_simulation(); } if (tmp) { goto while_3_break; } else { } } while_3_break: /* CIL Label */ ; } return; } }
void start_simulation(void) { int kernel_st ; int tmp ; int tmp___0 ; { { kernel_st = 0; update_channels(); init_threads(); fire_delta_events(); activate_threads(); reset_delta_events(); } { while (1) { while_6_continue: /* CIL Label */ ; { kernel_st = 1; eval(); } { kernel_st = 2; update_channels(); } { kernel_st = 3; fire_delta_events(); activate_threads(); reset_delta_events(); } { tmp = exists_runnable_thread(); } if (tmp == 0) { { kernel_st = 4; fire_time_events(); activate_threads(); reset_time_events(); } } else { } { tmp___0 = stop_simulation(); } if (tmp___0) { goto while_6_break; } else { } } while_6_break: /* CIL Label */ ; } return; } }
int main(int argc, char **argv) { int i; int val, longindex; int only_print = 0; int compare = 0; numthreads = 1; do { val = getopt_long(argc, argv, "t:pc", options, &longindex); switch (val) { case 't': numthreads = atoi(optarg); break; case 'p': only_print = 1; break; case 'c': compare = 1; break; } } while (val != EOF); if (optind >= argc) { printf("No tablebase specified.\n"); exit(0); } if (numthreads < 1) numthreads = 1; else if (numthreads > MAX_THREADS) numthreads = MAX_THREADS; total_work = (numthreads == 1) ? 1 : 100 + 10 * numthreads; init_threads(0); if (!compare) { if (!only_print) for (i = optind; i < argc; i++) verify_checksum(argv[i]); else for (i = optind; i < argc; i++) { char sum[40]; printf("%s: ", argv[i]); print_checksum(argv[i], sum); puts(sum); } } else { for (i = optind; i < argc; i++) compare_checksums(argv[i]); } return 0; }
static void init_once(void) { #ifndef _WIN32 /* Re-initialize the threadpool after fork. * Note that this discards the global mutex and condition as well * as the work queue. */ if (pthread_atfork(NULL, NULL, &reset_once)) abort(); #endif init_threads(); }
int main(int argc, char *argv[]){ if(parse_args(argc, argv)) print_usage_and_exit(); determine_num_threads(); if(allocate_states()) return 1; if(init_state(argc, argv)) print_usage_and_exit(); fill_table(); if(init_synchronization_objects()) return 1; if(init_threads()) return 1; uint64_t b, e; b = (statelen * nthreads) / (nthreads + 1); e = statelen - 1; // print_state(states[0]); int i; for(curstate = 1; gen <= gens; gen++){ curstate = !curstate; nthreads_left = nthreads - 1; wrap_state(states[curstate]); pthread_barrier_wait(&barrier); cnt = advance_gen_with_bounds(states[curstate], states[!curstate], b, e) + advance_gen_last_word (states[curstate], states[!curstate]); sem_wait(&sem); // print_state(states[!curstate]); for(i = 0; i < nthreads; i++){ cnt += cnts[i]; } cnt -= states[!curstate][0] & 0x01ul; if(cnt > maxpop){ maxpop = cnt; maxgen = gen; } else if(cnt < minpop){ minpop = cnt; mingen = gen; } } pthread_barrier_wait(&barrier); free_states(); if(join_threads()) return 1; if(destroy_synchronization_objects()) return 1; print_results(); return 0; }
int gfs2_make_fs_rw(struct gfs2_sbd *sdp) { struct gfs2_inode *ip = GFS2_I(sdp->sd_jdesc->jd_inode); struct gfs2_glock *j_gl = ip->i_gl; struct gfs2_holder freeze_gh; struct gfs2_log_header_host head; int error; error = init_threads(sdp); if (error) return error; error = gfs2_glock_nq_init(sdp->sd_freeze_gl, LM_ST_SHARED, 0, &freeze_gh); if (error) goto fail_threads; j_gl->gl_ops->go_inval(j_gl, DIO_METADATA); error = gfs2_find_jhead(sdp->sd_jdesc, &head); if (error) goto fail; if (!(head.lh_flags & GFS2_LOG_HEAD_UNMOUNT)) { gfs2_consist(sdp); error = -EIO; goto fail; } /* Initialize some head of the log stuff */ sdp->sd_log_sequence = head.lh_sequence + 1; gfs2_log_pointers_init(sdp, head.lh_blkno); error = gfs2_quota_init(sdp); if (error) goto fail; set_bit(SDF_JOURNAL_LIVE, &sdp->sd_flags); gfs2_glock_dq_uninit(&freeze_gh); return 0; fail: freeze_gh.gh_flags |= GL_NOCACHE; gfs2_glock_dq_uninit(&freeze_gh); fail_threads: kthread_stop(sdp->sd_quotad_process); kthread_stop(sdp->sd_logd_process); return error; }
int main(int argc, char *argv[]) { // Disable IO buffering setbuf(stdin, NULL); setbuf(stdout, NULL); std::cout.rdbuf()->pubsetbuf(NULL, 0); std::cin.rdbuf()->pubsetbuf(NULL, 0); // Initialization init_mersenne(); init_direction_table(); init_bitboards(); init_uci_options(); Position::init_zobrist(); Position::init_piece_square_tables(); MaterialInfo::init(); MovePicker::init_phase_table(); init_eval(1); init_bitbases(); init_threads(); // Make random number generation less deterministic, for book moves int i = abs(get_system_time() % 10000); for(int j = 0; j < i; j++) genrand_int32(); // Process command line arguments if(argc >= 2) { if(std::string(argv[1]) == "bench") { if(argc != 4) { std::cout << "Usage: glaurung bench <hash> <threads>" << std::endl; exit(0); } benchmark(std::string(argv[2]), std::string(argv[3])); return 0; } } // Print copyright notice std::cout << engine_name() << ". " << "Copyright (C) 2004-2008 Tord Romstad." << std::endl; // Enter UCI mode uci_main_loop(); return 0; }
Application::Application() { init_mersenne(); init_direction_table(); init_bitboards(); init_uci_options(); Position::init_zobrist(); Position::init_piece_square_tables(); init_eval(1); init_bitbases(); init_search(); init_threads(); // Make random number generation less deterministic, for book moves for (int i = abs(get_system_time() % 10000); i > 0; i--) genrand_int32(); }
int blosc_set_nthreads(int nthreads_new) { int32_t nthreads_old = nthreads; int32_t t; void *status; if (nthreads_new > BLOSC_MAX_THREADS) { fprintf(stderr, "Error. nthreads cannot be larger than BLOSC_MAX_THREADS (%d)", BLOSC_MAX_THREADS); return -1; } else if (nthreads_new <= 0) { fprintf(stderr, "Error. nthreads must be a positive integer"); return -1; } /* Only join threads if they are not initialized or if our PID is different from that in pid var (probably means that we are a subprocess, and thus threads are non-existent). */ if (nthreads > 1 && init_threads_done && pid == getpid()) { /* Tell all existing threads to finish */ end_threads = 1; /* Synchronization point for all threads (wait for initialization) */ WAIT_INIT; /* Join exiting threads */ for (t=0; t<nthreads; t++) { rc = pthread_join(threads[t], &status); if (rc) { fprintf(stderr, "ERROR; return code from pthread_join() is %d\n", rc); fprintf(stderr, "\tError detail: %s\n", strerror(rc)); exit(-1); } } init_threads_done = 0; end_threads = 0; } /* Launch a new pool of threads (if necessary) */ nthreads = nthreads_new; if (nthreads > 1 && (!init_threads_done || pid != getpid())) { init_threads(); } return nthreads_old; }
void start_simulation(void) { int kernel_st ; int tmp ; { { kernel_st = 0; update_channels(); init_threads(); fire_delta_events(); activate_threads(); reset_delta_events(); } { while (1) { while_1_continue: /* CIL Label */ ; { kernel_st = 1; eval(); } { kernel_st = 2; update_channels(); } { kernel_st = 3; fire_delta_events(); activate_threads(); reset_delta_events(); tmp = stop_simulation(); } if (tmp) { goto while_1_break; } else { } } while_1_break: /* CIL Label */ ; } return; } }
/**************************************************************************** * Standard kernel stuff ****************************************************************************/ void kernel_init(void) { /* Init the threading API */ init_threads(); /* Other processors will not reach this point in a multicore build. * In a single-core build with multiple cores they fall-through and * sleep in cop_main without returning. */ if (CURRENT_CORE == CPU) { memset(tick_funcs, 0, sizeof(tick_funcs)); memset(&all_queues, 0, sizeof(all_queues)); corelock_init(&all_queues.cl); tick_start(1000/HZ); #ifdef KDEV_INIT kernel_device_init(); #endif } }
/******************************************************************************* * NOME: main * FUNÇÃO: Chama as funcoes que iniciam as threads * * Tipo Descrição * pthread_t* Thread servidor declarada na main * pthread_t* Thread cliente declarada na main * * RETORNO: int (0 se threads foram criadas com sucesso, 1 se nao foram) *******************************************************************************/ int main(int argc,char **argv){ int erro = 0; prog_end = 0; client_add = 0; client_send = 0; numdecontatos = 0; char filename[25]; pthread_t serverthread, clientthread, menuthread; printf("Digite o numero da porta da aplicacao: "); scanf("%d", &PORTA); __fpurge(stdin); printf("Digite o seu endereco de IP: "); fgets(filename, 16, stdin); strtok(filename, "\n"); __fpurge(stdin); strcat(filename, "chat.txt"); chat_log = fopen(filename, "w+b"); if(chat_log == NULL){ printf("Erro na abertura do arquivo"); } else{ fputc('0', chat_log); } init_semaphores(); erro = init_threads(&serverthread, &clientthread, &menuthread); if (erro == 1){ //Significa que as threads nao foram criadas. Logo o programa nao pode prosseguir. return 1; } else{ pthread_join(menuthread, NULL); pthread_join(clientthread, NULL); return 0; } }
int main(int argc, char *argv[]) { if ( argc > 1 ){ if ( strcmp( argv[1], "-d" ) == 0 ){ memory.SERIAL2_DEBUG = 1; memory.showMonitorGUI = 0; } }else{ memory.SERIAL2_DEBUG = 0; memory.showMonitorGUI = 1; } init_sharedMemory(); printf("Shared Memory Initialized\n"); init_threads(); printf("Threads has been initialized\n"); main_loop(); printf(MSG_SYS_START); return 0; }
/******************************************************************************* * NOME: main * FUNÇÃO: Chama as funcoes que iniciam as threads * * Tipo Descrição * pthread_t* Thread servidor declarada na main * pthread_t* Thread cliente declarada na main * * RETORNO: int (0 se threads foram criadas com sucesso, 1 se nao foram) *******************************************************************************/ int main(int argc,char **argv){ int erro = 0; prog_end = 0; client_add = 0; client_send = 0; numdecontatos = 0; pthread_t serverthread, clientthread, menuthread; init_semaphores(); erro = init_threads(&serverthread, &clientthread, &menuthread); if (erro == 1){ //Significa que as threads nao foram criadas. Logo o programa nao pode prosseguir. return 1; } else{ pthread_join(menuthread, NULL); pthread_join(clientthread, NULL); pthread_join(serverthread, NULL); return 0; } }
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR CmdLine, int nShow) { WNDCLASS wc; HWND wnd; MSG msg; init_threads (); init_functions (); wc.style = 0; wc.lpfnWndProc = MainWndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInst; wc.hIcon = 0; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = CreateSolidBrush(RGB(0, 0, 0)); wc.lpszMenuName = 0; wc.lpszClassName = "MandClass"; if (!RegisterClass(&wc)) return 1; init_bi(); wnd = CreateWindow("MandClass", "M-View", WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, hInst, 0); if (!wnd) return 1; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return 0; }
void * init_space(void *arg){ struct tuple *tuple = (struct tuple *) arg; //init hteachers Runner_Arg *args = malloc(sizeof(Runner_Arg)); if (!args){ perror("MEM :"); exit(-1); } pthread_mutex_t *read_fd = malloc(sizeof(pthread_mutex_t )); if (!read_fd){ perror("MEM:"); exit(-1); } args->fd =fdopen(tuple->fd, "r"); if (args->fd == NULL) return error_("Could not create file from pipe reading end"); args->read_fd_lock = read_fd; if (pthread_mutex_init(read_fd, NULL)!=0) return error_("Initializing mutex failed: "); init_threads(args, tuple->users -1, space_runner); //this thread runs staff_runner . new Staffs runners are launched by that method. return space_runner(args); }
void * init_staff(void *arg){ struct tuple *tuple = (struct tuple *) arg; //init hteachers Runner_Arg *args = malloc(sizeof(Runner_Arg)); if (!args){ perror("MEM :"); exit(-1); } pthread_mutex_t *read_fd = malloc(sizeof(pthread_mutex_t)); if (!read_fd){ perror("MEM :"); exit(-1); } args->fd =fdopen(tuple->fd, "r"); if (args->fd == NULL) return error_("Could not create file from pipe reading end\n"); args->read_fd_lock = read_fd; if (pthread_mutex_init(read_fd, NULL)!=0) return error_("Initializing mutex failed: \n"); // init n- 1 threads... init_threads(args, tuple->users -1, staff_runner); //because we run a thread already: return staff_runner(args); }
int main(int argc, char **argv) { init_needle(argc > 1 ? argv[1] : "GCAACGAGTGTCTTTG"); #ifdef DNA_DEBUG printf("Looking for %s\n", needle); #endif struct timeval start_time; print_current_time(&start_time); printf(" START\n"); bufindex_t input_size = 3000000000L; size_t page_size = sysconf(_SC_PAGESIZE); ASSERT_NOT(page_size & (page_size - 1), "Page is not a power of 2"); size_t mask = page_size - 1; size_t mem_size = (input_size | mask) + 1; buflen_t buf_size = page_size << 14; #ifdef DNA_DEBUG printf("Buf size = %u\n", buf_size);; #endif init_threads(); ALGO_PREPARE #ifdef DNA_DEBUG long io_time, waiting_time; struct timeval tx, ty, tz; print_current_time(&tx); printf(" Start reading data\n"); #endif int fd = 0; if (argc > 2 && (fd = open(argv[2], O_RDONLY)) == -1) ERROR_OCCURRED("open"); char *mapped_file = mmap(NULL, mem_size, PROT_READ, MAP_SHARED, fd, 0); if (fd > 0 && close(fd) == -1) ERROR_OCCURRED("close"); char *buf; bufindex_t start; buflen_t bytes_read; buflen_t len = buf_size + needle_len - 1; for (start = 0, buf = mapped_file; start < input_size; start += buf_size, buf += buf_size) { bytes_read = (start + len < input_size) ? len : input_size - start; job_t *job = malloc(sizeof(job_t)); job->buf = buf; job->len = bytes_read; job->offset = start; submit_job(job); } #ifdef DNA_DEBUG print_current_time(&ty); printf(" End submitting jobs\n"); io_time = calc_elapsed_time(&tx, &ty); #endif wait_jobs_completed(); munmap(mapped_file, mem_size); #ifdef DNA_DEBUG gettimeofday(&tz, NULL); waiting_time = calc_elapsed_time(&ty, &tz); #endif destroy_threads(); ALGO_FREE struct timeval end_time; print_current_time(&end_time); printf(" FINISH\n"); #ifdef DNA_DEBUG print_elapsed_time(&start_time, &end_time); printf("I/O: %ld\n", io_time); printf("Waiting: %ld\n", waiting_time); #endif return 0; }
int main ( int argc, char *argv[] ) { pwr_tStatus sts; int event; plc_sProcess *pp; uid_t ruid; struct passwd *pwd; /* struct rlimit rlim; int i; */ /* Set core dump file size limit to infinite */ /* rlim.rlim_cur = RLIM_INFINITY; rlim.rlim_max = RLIM_INFINITY; sts = setrlimit(RLIMIT_CORE, &rlim); printf("%d\n", sts); i = 1/0; printf("%d\n", i); */ pp = init_process(); qcom_WaitAnd(&sts, &pp->eventQ, &qcom_cQini, ini_mEvent_newPlcInit, qcom_cTmoEternal); init_plc(pp); create_threads(pp); init_threads(pp); /* Once threads has set their priority don't run as root */ #if 0 ruid = getuid(); if (ruid == 0) { pwd = getpwnam("pwrp"); if (pwd != NULL) { setreuid(pwd->pw_uid, pwd->pw_uid); } } else setreuid(ruid, ruid); #endif qcom_SignalOr(&sts, &qcom_cQini, ini_mEvent_newPlcInitDone); qcom_WaitAnd(&sts, &pp->eventQ, &qcom_cQini, ini_mEvent_newPlcStart, qcom_cTmoEternal); // proc_SetPriority(pp->PlcProcess->Prio); set_values(pp); start_threads(pp); run_threads(pp); time_Uptime(&sts, &pp->PlcProcess->StartTime, NULL); qcom_SignalOr(&sts, &qcom_cQini, ini_mEvent_newPlcStartDone); #if 0 /* Force the backup to take care initialized backup objects. */ bck_ForceBackup(NULL); #endif errh_SetStatus( PWR__SRUN); qcom_WaitOr(&sts, &pp->eventQ, &qcom_cQini, ini_mEvent_terminate | ini_mEvent_oldPlcStop, qcom_cTmoEternal, &event); switch ( event) { case ini_mEvent_terminate: errh_SetStatus( PWR__SRVTERM); stop_threads(pp); clean_all(pp); nmps_delete_lock( &sts); break; case ini_mEvent_oldPlcStop: errh_SetStatus( PWR__SRVTERM); time_Uptime(&sts, &pp->PlcProcess->StopTime, NULL); stop_threads(pp); save_values(pp); qcom_SignalOr(&sts, &qcom_cQini, ini_mEvent_oldPlcStopDone); #if defined OS_ELN sts = proc_SetPriority(31); #endif clean_all(pp); break; default: ; } exit(0); }
/* @Test */ void test_pop3(void) { struct list pop3_list; struct account *ac; struct pop3_server *pop3_server; struct pop3_dl_options dl_options = {0}; char *profile_path; char *pwd; debug_init(); debug_set_level(25); pwd = realpath(".", NULL); CU_ASSERT(pwd != NULL); profile_path = mycombinepath(pwd, "test-account-profile"); CU_ASSERT(profile_path != NULL); config_set_user_profile_directory(profile_path); CU_ASSERT(codesets_init() != 0); CU_ASSERT(progmon_init() != 0); CU_ASSERT(init_threads() != 0); CU_ASSERT(load_config() != 0); CU_ASSERT(init_folders() != 0); ac = account_malloc(); CU_ASSERT(ac != NULL); CU_ASSERT(ac->imap != NULL); CU_ASSERT(ac->pop != NULL); ac->recv_type = 0; if (ac->pop->name) free(ac->pop->name); ac->pop->name = mystrdup("localhost"); CU_ASSERT(ac->pop->name != NULL); if (ac->pop->login) free(ac->pop->login); ac->pop->login = mystrdup("test"); CU_ASSERT(ac->pop->login != NULL); if (ac->pop->passwd) free(ac->pop->passwd); ac->pop->passwd = mystrdup("test"); CU_ASSERT(ac->pop->passwd != NULL); ac->pop->ssl = 0; ac->pop->port = 10110; insert_config_account(ac); mails_test_account(ac, mails_test_account_callback); sleep(3); account_free(ac); cleanup_threads(); del_folders(); free_config(); progmon_deinit(); codesets_cleanup(); free(profile_path); free(pwd); }
int main(int argc, char **argv) { char c; init_settings(); setbuf(stderr,NULL); if (argc < 2) { usage(argv[0]); exit(EXIT_FAILURE); } while (-1 != (c = getopt(argc, argv, "F:" "D:" "T:" "N:" "W:" "f:" ))) { switch(c) { case 'F': bench_desc.log_file_dir = optarg; break; case 'D': bench_desc.dir_path = optarg; break; case 'T': bench_desc.num_threads = atoi(optarg); if (bench_desc.num_threads < 1) { fprintf(stderr, "Number of threads (T) must be greater than 0\n"); exit(EXIT_FAILURE); } if (bench_desc.num_threads > MAX_THREADS) { fprintf(stderr, "WARNING: Number of threads (T) is too large. " "This is not recommended and may lead to weird " "behavior.\n"); } break; case 'N': bench_desc.num_files = atoi(optarg); break; case 'W': if (strcasecmp(optarg, "create") == 0) bench_desc.workload_type = CREATE_WORKLOAD; else if (strcasecmp(optarg, "lookup") == 0) bench_desc.workload_type = LOOKUP_WORKLOAD; else if (strcasecmp(optarg, "scan") == 0) { bench_desc.workload_type = SCAN_WORKLOAD; bench_desc.num_threads = 1; } else if (strcasecmp(optarg, "mixed") == 0) bench_desc.workload_type = MIXED_WORKLOAD; else { fprintf(stderr, "Invalid workload (w): %s \n" "We only support: create, lookup, scan or mixed." "\n",optarg); exit(EXIT_FAILURE); } break; case 'f': if (bench_desc.workload_type == MIXED_WORKLOAD) { bench_desc.mixed_frac = atof(optarg); if ((bench_desc.mixed_frac < 0.0) || (bench_desc.mixed_frac > 1.0)) fprintf(stderr, "range of mixed_frac (f) is [0.0-1.0] \n"); exit(EXIT_FAILURE); } else fprintf(stderr, "WARNING: mixed_frac (f) is valid only with " "mixed workloads (-O m). We will default it to " "an all create workload. \n"); default: fprintf(stderr, "Illegal parameter: %c\n", c); break; } } print_settings(); init_threads(); return 1; }
int main(long argc, char** argv) { int i, j; long t; FILE* fp; double duration; clock_t time; struct timeval tpstart, tpend; long iTimeInterval; int Test = 0; if (argc != 4) { printf("usage: %s .max_graph_file num_threads GR frequency\n", argv[0]); exit(-1); } num_threads = atoi(argv[2]); fprintf(stderr, "Threads: \t\t%d\n", num_threads); // initialize the graph, will read the graph from a file. fp = fopen(argv[1], "r"); if (!fp) { printf("Cannot open %s\n", argv[1]); exit(-1); } char tag; char str[5]; int from, to, capacity; fscanf(fp, "%c", &tag); while (tag != 'p') { while (getc(fp) != '\n') ; fscanf(fp, "%c", &tag); } fscanf(fp, "%s %d %d", str, &g_num_nodes, &g_num_edges); gr_threshold = (int)(atof(argv[3]) * g_num_nodes); fprintf(stderr, "GR Freq: \t\t%2.2f\n", atof(argv[3])); fprintf(stderr, "%d nodes, %d edges\n\n", g_num_nodes, g_num_edges); // initialize graph init_graph(); // read and sort edges Edge edge = (Edge)malloc(2 * g_num_edges * sizeof(struct edge_entry)); if (edge == NULL) exit(-1); edge_sym = edge; edgecnt = 0; for (i = 0; i < g_num_edges;) { if (getc(fp) == 'a') { fscanf(fp, "%d %d %d/n", &from, &to, &capacity); edge = Addedge(from - 1, to - 1, capacity, 0, edge); i++; } } assert(i == g_num_edges); SortEdges(); fprintf(stderr, "Edge sorted!\n"); // initialize thread parameters init_threads(num_threads); pthread_t threads[num_threads]; // initial barrier and lock pthread_mutex_init(&(gr_mutex), NULL); node_mutex = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t) * g_num_nodes); if (node_mutex == NULL) exit(-1); thread_mutex = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t) * num_threads); if (thread_mutex == NULL) exit(-1); for (i = 0; i < num_threads; i++) { pthread_mutex_init(&(thread_mutex[i]), NULL); } for (i = 0; i < g_num_nodes; i++) { pthread_mutex_init(&(node_mutex[i]), NULL); } pthread_barrier_init(&start_barrier, NULL, num_threads); // now the f c e h arrays have been initialized. start the threads // so that they can work asynchronously. time = clock(); gettimeofday(&tpstart, NULL); preflow(num_threads); for (t = 0; t < num_threads; t++) { pthread_create(&(threads[t]), NULL, scan_nodes, (void*)t); } #ifdef MONITOR int num_idle_threads; int totalQsize, global_Q_size; while (!flow_done()){ gettimeofday(&tpend, NULL); iTimeInterval = 1000000 * (tpend.tv_sec - tpstart.tv_sec); iTimeInterval += tpend.tv_usec - tpstart.tv_usec; duration = (double)iTimeInterval / 1000000; totalQsize = 0; num_idle_threads = 0; for (j = 0; j < num_threads; j++) { totalQsize += threadEnv[j].Qsize; if (threadEnv[j].Qsize == 0) num_idle_threads++; } if (duration > 10.0) { fprintf(stderr, " totalQsize: %8d globalQsize %4d idle %2d\n", totalQsize, global_Q_size, num_idle_threads); fflush(stderr); exit(-1); } // printf("%12d %12d \t\t totalQsize: %8d GR %4d idel %2d\n", // g_node[0].excess,g_node[g_num_nodes-1].excess, totalQsize, GRcnt, // num_idle_threads); // printf("%d\n", totalQsize); } printf("\n"); #endif for (t = 0; t < num_threads; t++) { pthread_join(threads[t], NULL); } gettimeofday(&tpend, NULL); time = clock() - time; iTimeInterval = 1000000 * (tpend.tv_sec - tpstart.tv_sec); iTimeInterval += tpend.tv_usec - tpstart.tv_usec; duration = (double)iTimeInterval / 1000000; fprintf(stderr, "FLOW: \t\t\t%ld\n", sink->excess); fprintf(stderr, "Wall Time: \t\t%5.3f\n", duration); fprintf(stderr, "CPU Time: \t\t%5.3f\n", (double)time / CLOCKS_PER_SEC / num_threads); fprintf(stderr, "Push: \t\t\t%ld\n", totalPushes); fprintf(stderr, "Push Efcy: \t\t%.1f\n", totalPushes / duration); fprintf(stderr, "Lift: \t\t\t%ld\n", totalLifts); fprintf(stderr, "Lift Efcy: \t\t%.1f\n", totalLifts / duration); fprintf(stderr, "GR: \t\t\t%d\n", GRcnt); fprintf(stderr, "HELP: \t\t\t%d\n", HPcnt); fflush(stderr); check_violation(); pthread_exit(NULL); }
int main() { init_threads(); wait_for_threads(); return 0; }
int rtapi_app_main(void) { int retval; rtapi_print_msg(RTAPI_MSG_INFO, "MOTION: init_module() starting...\n"); /* set flag */ first_pass = 1; /* connect to the HAL and RTAPI */ mot_comp_id = hal_init("motmod"); if (mot_comp_id < 0) { rtapi_print_msg(RTAPI_MSG_ERR, _("MOTION: hal_init() failed\n")); return -1; } if (( num_joints < 1 ) || ( num_joints > EMCMOT_MAX_JOINTS )) { rtapi_print_msg(RTAPI_MSG_ERR, _("MOTION: num_joints is %d, must be between 1 and %d\n"), num_joints, EMCMOT_MAX_JOINTS); return -1; } if (( num_dio < 1 ) || ( num_dio > EMCMOT_MAX_DIO )) { rtapi_print_msg(RTAPI_MSG_ERR, _("MOTION: num_dio is %d, must be between 1 and %d\n"), num_dio, EMCMOT_MAX_DIO); return -1; } if (( num_aio < 1 ) || ( num_aio > EMCMOT_MAX_AIO )) { rtapi_print_msg(RTAPI_MSG_ERR, _("MOTION: num_aio is %d, must be between 1 and %d\n"), num_aio, EMCMOT_MAX_AIO); return -1; } /* initialize/export HAL pins and parameters */ retval = init_hal_io(); if (retval != 0) { rtapi_print_msg(RTAPI_MSG_ERR, _("MOTION: init_hal_io() failed\n")); hal_exit(mot_comp_id); return -1; } /* allocate/initialize user space comm buffers (cmd/status/err) */ retval = init_comm_buffers(); if (retval != 0) { rtapi_print_msg(RTAPI_MSG_ERR, _("MOTION: init_comm_buffers() failed\n")); hal_exit(mot_comp_id); return -1; } /* set up for realtime execution of code */ retval = init_threads(); if (retval != 0) { rtapi_print_msg(RTAPI_MSG_ERR, _("MOTION: init_threads() failed\n")); hal_exit(mot_comp_id); return -1; } rtapi_print_msg(RTAPI_MSG_INFO, "MOTION: init_module() complete\n"); hal_ready(mot_comp_id); old_handler = rtapi_get_msg_handler(); rtapi_set_msg_handler(emc_message_handler); return 0; }
void run(void) { #if DEBUG_RUNS int count = 0; #endif init_poller(); // Initialize binary image state initialize_binary(); // Initialize memory { TWOBYTES size; memory_init (); #if SEGMENTED_HEAP size = EXTRA_MEMORY_SIZE; region = (byte *) malloc (size * sizeof (TWOBYTES)); memory_add_region (region, region + size * sizeof (TWOBYTES)); #endif size = MEMORY_SIZE; region = (byte *) malloc (size * sizeof (TWOBYTES)); memory_add_region (region, region + size * sizeof (TWOBYTES)); } // Initialize exceptions init_exceptions(); // Create the boot thread (bootThread is a special global) bootThread = (Thread *) new_object_for_class (JAVA_LANG_THREAD); #if DEBUG_THREADS printf ("Created bootThread: %d. Initializing...\n", (int) bootThread); #endif #if DEBUG_RUNS for (count = 0; count < 100; count++) { #endif // DEBUG_RUNS #if DEBUG_RCX_MEMORY { TWOBYTES numNodes, biggest, freeMem; scan_memory (&numNodes, &biggest, &freeMem); printf ("nodes = %d\n", (int) numNodes); printf ("biggest = %d\n", (int) biggest); printf ("freeMem = %d\n", (int) freeMem); } #endif init_threads(); if (!init_thread (bootThread)) { printf ("Unable to initialize threading module.\n"); exit (1); } // Execute the bytecode interpreter set_program_number (0); #if DEBUG_STARTUP printf ("Engine starting.\n"); #endif engine(); // Engine returns when all non-daemon threads are dead #if DEBUG_STARTUP printf ("Engine finished.\n"); #endif #if DEBUG_RUNS } #endif // DEBUG_RUNS }
static Uint32 download_files(update_info_t* infos, const Uint32 count, const char* server, const char* path, const Uint32 source_count, unzFile* sources, zipFile dest, progress_fnc update_progress_function, void* user_data) { char file_name[256]; download_files_thread_data_t thread_data; FILE *file; Uint64 len; Uint32 i, j, download, error, index; #ifdef WINDOWS file = my_tmpfile(); #else file = tmpfile(); #endif if (file == 0) { return 1; } error = 0; init_threads(&thread_data, count, server, path, dest, update_progress_function, user_data); for (i = 0; i < count; i++) { CHECK_AND_LOCK_MUTEX(thread_data.mutex); index = thread_data.index; CHECK_AND_UNLOCK_MUTEX(thread_data.mutex); if (update_progress_function("Updating files", count, index, user_data) != 1) { error = 2; break; } download = 1; len = strlen(infos[i].file_name); safe_snprintf(file_name, sizeof(file_name), "%s", infos[i].file_name); if (has_suffix(file_name, len, ".xz", 3)) { file_name[len - 3] = 0; } for (j = 0; j < source_count; j++) { if (check_md5_from_zip(sources[j], file_name, infos[i].digest) == 0) { CHECK_AND_LOCK_MUTEX(thread_data.mutex); copy_from_zip(sources[j], dest); thread_data.index++; CHECK_AND_UNLOCK_MUTEX(thread_data.mutex); download = 0; break; } } if (download == 1) { queue_push(thread_data.files, &infos[i]); SDL_CondSignal(thread_data.condition); } } wait_for_threads(&thread_data, &error); fclose(file); return error; }
int main (int argc, char **argv) { fz_context *context; int *pageinfo = NULL; /* int i; */ /* Initialises mutexes required for Fitz locking */ init_least_context_locks(); context = fz_new_context(NULL, &least_context_locks, FZ_STORE_DEFAULT); if (!context) fprintf(stderr, "Failed to create context\n"); if (force_thread_count) thread_count = force_thread_count; else thread_count = sysconf(_SC_NPROCESSORS_ONLN); if (argc == 2) { /* Initialize OpenGL window */ setup_sdl(); /* Start render threads */ init_threads(thread_count, context); /* * At this point, we should have a properly setup * double-buffered window for use with OpenGL. */ setup_opengl(w, h); init_busy_texture(); /* Check for non-power-of-two support */ /* printf("Extensions are: %s\n", glGetString(GL_EXTENSIONS)); */ if (strstr((const char *)glGetString(GL_EXTENSIONS), "GL_ARB_texture_non_power_of_two")) { puts("Machine supports NPOT textures."); power_of_two = 0; } else { puts("Machine supports POT textures only."); power_of_two = 1; } power_of_two |= force_power_of_two; /* Load textures from PDF file */ open_pdf(context, argv[1]); /* * Now we want to begin our normal app process-- * an event loop with a lot of redrawing. */ while (1) { /* Process incoming events. */ process_events(); /* Update cache state */ update_cache(); if (redraw) { /* glDeleteTextures(pagec, pages); open_pdf(context, argv[1]); */ redraw = 0; draw_screen(); } /* pageinfo = NULL; for(i = 0; i < visible_pages(pageinfo); i++) { printf("%d, ", i); } printf("\n"); */ free(pageinfo); } } fz_close_document(doc); fz_free_context(context); return 0; }
int main(int argn,char *argv[]) { // Print version printf("Fred ver. %s\n",VERSION); // Read command line arguments init_cmds_line_args(argn,argv); // Creates thread init_threads(); // Creates channels init_speaker_pipe(); // Init buttons init_buttons(); // Main loop //char job_choise = 0; char buttons_choise; while(1) { // Read GPIO /* printf("\n\n\n\n\nOpzioni:\n1) Posizione\n2) Beccheggio\n3) Rollio\n4)" " Impostazione posizione iniziale\n5) Uscita\nScelta:"); scanf(" %c",&job_choise); if(job_choise == '1') write(PIPE_CHANNEL[1],"1", 1); if(job_choise == '2') write(PIPE_CHANNEL[1],"2", 1); if(job_choise == '3') write(PIPE_CHANNEL[1],"3", 1); if(job_choise == '4') write(PIPE_CHANNEL[1],"4", 1); if(job_choise == '5') { // Request exit to speaker thread write(PIPE_CHANNEL[1],"5", 1); // Terminates the get_compass_data thread pthread_cancel(get_compass_data_thread); break; } */ buttons_choise = read_buttons(); // Send info to speaker if(buttons_choise & BTN_GET_POSITION) write(PIPE_CHANNEL[1],"1", 1); if(buttons_choise & BTN_GET_PICH) write(PIPE_CHANNEL[1],"2", 1); if(buttons_choise & BTN_GET_ROLL) write(PIPE_CHANNEL[1],"3", 1); if(buttons_choise & BTN_SET_POSITION) write(PIPE_CHANNEL[1],"4", 1); if(buttons_choise & BTN_POWER_OFF) { // Request exit to speaker thread write(PIPE_CHANNEL[1],"5", 1); // Terminates the get_compass_data thread pthread_cancel(get_compass_data_thread); break; } sleep(1); } // Wait for last cmd sleep(5); // Close the pipe channels close(PIPE_CHANNEL[0]); close(PIPE_CHANNEL[1]); // Wait for the end of the thread pthread_join(get_compass_data_thread,NULL); pthread_join(speaker_thread,NULL); return EXIT_SUCCESS; }