int main(int argc, const char* argv[]) { threadpool thpool; struct __workq WorkQ; int i; begin: srand(time(NULL)); WorkQ.cnt = 0; PCHECK(pthread_mutex_init(&WorkQ.lock, NULL)); PCHECK(pthread_cond_init(&WorkQ.got_consumer_cond, NULL)); PCHECK(pthread_cond_init(&WorkQ.got_producer_cond, NULL)); TAILQ_INIT(&WorkQ.head); if (!(thpool = thpool_init(PRODUCER_THREAD_NUM + CONSUMER_THREAD_NUM))) { errx(EXIT_FAILURE, "thpool_init() error.\n"); } /* 消费者线程 */ for (i = 0; i < CONSUMER_THREAD_NUM; i++) { thpool_add_work(thpool, consumer, &WorkQ); } sleep(2); /* 生产者线程 */ for (i = 0; i < PRODUCER_THREAD_NUM; i++) { thpool_add_work(thpool, producer, &WorkQ); } end: thpool_wait(thpool); thpool_destroy(thpool); exit(EXIT_SUCCESS); }
/** * Fire up the swarm engine, and return its context * @param protocol_handlers the protocol handlers * @param datastore the datastore * @param filestore the file store * @returns the SwarmContext */ struct SwarmContext* libp2p_swarm_new(struct Libp2pVector* protocol_handlers, struct Datastore* datastore, struct Filestore* filestore) { struct SwarmContext* context = (struct SwarmContext*) malloc(sizeof(struct SwarmContext)); if (context != NULL) { context->thread_pool = thpool_init(25); context->protocol_handlers = protocol_handlers; context->datastore = datastore; context->filestore = filestore; } return context; }
char getBestMove(char subBoard[], char superBoard[], char superBoardSpot, char opPlayer, char levels) { long best = -9999999999; char move; char start, end; char j = 0; char lastSuperBoardState; if (superBoardSpot == -1) { //search all spots on the board start = 0; end = SUB_BOARD_SIZE; } else { start = superBoardSpot * 9; end = start + 9; } threadpool thpool = thpool_init(THREADS); //search within the superboard for (char i = start; i < end; i++) { if (isOpenSpot(subBoard, superBoard, i)) { //Take the winning move is available lastSuperBoardState = superBoard[(i - (i % 9)) / 9]; char newSuperBoardSpot = doMove(subBoard, superBoard, opPlayer, i); if (superBoardWon(superBoard) == opPlayer) { undoMove(subBoard, superBoard, i, lastSuperBoardState); return i; } undoMove(subBoard, superBoard, i, lastSuperBoardState); ThreadData data; data.subBoard = copyBoard(subBoard, SUB_BOARD_SIZE); data.superBoard = copyBoard(superBoard, SUPER_BOARD_SIZE); data.opPlayer = opPlayer; data.levels = levels; data.move = i; tData[j] = data; thpool_add_work(thpool, (void*)threadStarter, j++); } } numThreads = j; thpool_wait(thpool); for (char i = 0; i < numThreads; i++) { if (trData[i].score > best) { best = trData[i].score; move = trData[i].move; } } return move; }
int main(void) { struct thpool *pool = thpool_init(10, 20); thpool_add_job(pool, work, "1"); thpool_add_job(pool, work, "2"); thpool_add_job(pool, work, "3"); thpool_add_job(pool, work, "4"); thpool_add_job(pool, work, "5"); thpool_add_job(pool, work, "6"); thpool_add_job(pool, work, "7"); thpool_add_job(pool, work, "8"); thpool_add_job(pool, work, "9"); thpool_add_job(pool, work, "10"); thpool_add_job(pool, work, "11"); thpool_add_job(pool, work, "12"); thpool_add_job(pool, work, "13"); thpool_add_job(pool, work, "14"); thpool_add_job(pool, work, "15"); thpool_add_job(pool, work, "16"); thpool_add_job(pool, work, "17"); thpool_add_job(pool, work, "18"); thpool_add_job(pool, work, "19"); thpool_add_job(pool, work, "20"); thpool_add_job(pool, work, "21"); thpool_add_job(pool, work, "22"); thpool_add_job(pool, work, "23"); thpool_add_job(pool, work, "24"); thpool_add_job(pool, work, "25"); thpool_add_job(pool, work, "26"); thpool_add_job(pool, work, "27"); thpool_add_job(pool, work, "28"); thpool_add_job(pool, work, "29"); thpool_add_job(pool, work, "30"); thpool_add_job(pool, work, "31"); thpool_add_job(pool, work, "32"); thpool_add_job(pool, work, "33"); thpool_add_job(pool, work, "34"); thpool_add_job(pool, work, "35"); thpool_add_job(pool, work, "36"); thpool_add_job(pool, work, "37"); thpool_add_job(pool, work, "38"); thpool_add_job(pool, work, "39"); thpool_add_job(pool, work, "40"); sleep(5); thpool_destroy(pool); return 0; }
int main(int argc, char *argv[]){ char* p; if (argc != 2){ puts("This testfile needs excactly one arguments"); exit(1); } int num_threads = strtol(argv[1], &p, 10); threadpool thpool = thpool_init(num_threads); thpool_destroy(thpool); sleep(1); // Sometimes main exits before thpool_destroy finished 100% return 0; }
int main (int argc, char* argv[]) { thpool_init (100); int *arg = (int *) malloc (sizeof (int) * 1000); int i; for (i=0; i<1000; i++) { arg[i] = i; thpool_add_worker (myprocess, &arg[i]); } sleep(6); thpool_destroy(); free(arg); return 0; }
int main(){ puts("Making threadpool with 4 threads"); threadpool thpool = thpool_init(4); puts("Adding 40 tasks to threadpool"); int i; for (i=0; i<20; i++){ thpool_add_work(thpool, (void*)task1, NULL); thpool_add_work(thpool, (void*)task2, NULL); }; puts("Killing threadpool"); thpool_destroy(thpool); return 0; }
int main() { printf("~~~~~~~~~~~"); thpool_t* thpool; int i; thpool = thpool_init(5); puts("Adding 20 tasks to threadpool"); //int a=54; for (i=0; i<20; i++){ thpool_add_work(thpool, (void*)task1, NULL); thpool_add_work(thpool, (void*)task2, NULL); }; puts("Will kill threadpool"); thpool_destroy(thpool); }
int main(){ nonzero_stack(); nonzero_heap(); puts("Making threadpool with 4 threads"); threadpool thpool = thpool_init(4); puts("Adding 20 tasks to threadpool"); int i; for (i=0; i<20; i++){ thpool_add_work(thpool, (void*)task, NULL); }; puts("Killing threadpool"); thpool_destroy(thpool); return 0; }
int main(){ intptr_t i; thpool_t* threadpool; /* make a new thread pool structure */ threadpool=thpool_init(4); /* initialise it to 4 number of threads */ puts("Adding 20 tasks to threadpool"); for (i=0; i<10; i++){ thpool_add_work(threadpool, i, (void *)task1, NULL); thpool_add_work(threadpool, i, (void *)task2, (void *)i); }; puts("Will kill threadpool"); thpool_destroy(threadpool); return 0; }
int main() { int level = 14; //time stuff struct timeval t1, t2; double elapsedTime1, elapsedTime2; printf("Starting none threaded\n"); // start timer gettimeofday(&t1, NULL); levels(level); // stop timer gettimeofday(&t2, NULL); elapsedTime1 = (t2.tv_sec - t1.tv_sec); threadpool thpool = thpool_init(2); // start timer gettimeofday(&t1, NULL); level--; for (int i = 0; i < level; i++) { thpool_add_work(thpool, (void*)levels, level); } thpool_wait(thpool); // stop timer gettimeofday(&t2, NULL); elapsedTime2 = (t2.tv_sec - t1.tv_sec); printf("done\n"); printf("None threaded seconds: %f\n", elapsedTime1); printf("Threaded seconds: %f\n", elapsedTime2); }
int main(int argc, char *argv[]){ char* p; if (argc != 3){ puts("This testfile needs excactly two arguments"); exit(1); } int num_jobs = strtol(argv[1], &p, 10); int num_threads = strtol(argv[2], &p, 10); threadpool thpool = thpool_init(num_threads); int n; for (n=0; n<num_jobs; n++){ thpool_add_work(thpool, (void*)increment, NULL); } thpool_wait(thpool); printf("%d\n", sum); return 0; }
int main() { FILE *pFile = NULL; int lineCnt = 0; int i = 0; ipList_t* ipList = NULL; /*thread pool 갯수 지정 */ threadpool thpool = thpool_init(THREAD_CNT); /* 읽을 파일의 라인수를 체크 */ lineCnt = lineCount(CHECKLIST_FILE_PATH); printf("lineCnt :[%d] \n",lineCnt); ipList = (ipList_t*)malloc(sizeof(ipList_t)*(lineCnt+10)); memset(ipList,0x00, sizeof(ipList_t)*(lineCnt+10)); pFile = fopen( CHECKLIST_FILE_PATH, "r" ); if( pFile != NULL ) { char strTemp[255]; char *pStr; while( !feof( pFile ) ) { char* ss = NULL; pStr = fgets( strTemp, sizeof(strTemp), pFile ); printf( "pStr:[%s] \n", pStr ); printf( "strTemp:[%s] \n", strTemp ); if(pStr != NULL) { pStr = rtrim(pStr); char* trimStr; //strncpy((ipList+i)->ip, pStr, STR_LEN); //ipList+0 번째가 깨진다. strcpy((ipList+i)->ip, pStr); i++; } } fclose( pFile ); } for(i =0 ;i < lineCnt;i++) { printf("ipList[%d]:[%s] \n",i,(ipList+i)->ip); thpool_add_work(thpool, (void*)pingChk, (ipList+i)->ip); } thpool_wait(thpool); thpool_destroy(thpool); free(ipList); #if 0 pthread_t p_thread[THREAD_CNT]; int thr_id; //쓰레드ID int status; //char p1[] = "thread_1"; // 1번 쓰레드 이름 //char p2[] = "thread_2"; // 2번 쓰레드 이름 //char pM[] = "thread_m"; // 메인 쓰레드 이름 // 파일 읽기 if(fRead() == ERROR) { printf("FRead Error \n"); } Fread(); sleep(2); // 2초 대기후 쓰레드 생성 sys // ① 1번 쓰레드 생성 // 쓰레드 생성시 함수는 t_function // t_function 의 매개변수로 p1 을 넘긴다. thr_id = pthread_create(&p_thread[0], NULL, t_function, (void *)p1); // pthread_create() 으로 성공적으로 쓰레드가 생성되면 0 이 리턴됩니다 if (thr_id < 0) { perror("thread create error : "); exit(0); } // ② 2번 쓰레드 생성 thr_id = pthread_create(&p_thread[1], NULL, t_function, (void *)p2); if (thr_id < 0) { perror("thread create error : "); exit(0); } // ③ main() 함수에서도 쓰레드에서 돌아가고 있는 동일한 함수 실행 //t_function((void *)pM); // 쓰레드 종료를 기다린다. pthread_join(p_thread[0], (void **)&status); pthread_join(p_thread[1], (void **)&status); printf("언제 종료 될까요?\n"); #endif return SUCCESS; }
// Main function, the base TCP server int main(int argc, char *argv[]) { //-------------------- SET UP VARIABLES ----------------------- // Set up all required variables for sockets programming, starting with addrinfo "hints" struct and pointers to results list struct addrinfo hints, *result; // Integer variable used to set socket options int yes = 1; // Create command buffer, to send commands directly to the server char command[512] = { '\0' }; // Define a generic indexer variable for loops int i = 0; // Set up SQLite statement struct sqlite3_stmt *stmt; // Create a buffer to store queries to process on the database char query[256] = { '\0' }; //------------------ INITIALIZE SIGNAL HANDLERS --------------- // Install signal handlers for graceful shutdown // Install SIGHUP signal handler signal(SIGHUP, shutdown_handler); // Install SIGINT signal handler signal(SIGINT, shutdown_handler); // Install SIGTERM signal handler signal(SIGTERM, shutdown_handler); // Install signal handlers for statistics output // Install SIGUSR1 signal handler signal(SIGUSR1, stat_handler); // Install SIGUSR2 signal handler signal(SIGUSR2, stat_handler); //------------------ BEGIN SERVER INITIALIZATION -------------- // Read in terminal on which server was started term = strdup(ttyname(1)); // Print initialization message fprintf(stdout, "%s: %s %s - Justin Hill, Gordon Keesler, Matt Layher (CS5550 Spring 2012)\n", SERVER_NAME, INFO_MSG, SERVER_NAME); // Capture initial start time start_time = time(NULL); //------------------ PARSE COMMAND LINE ARGUMENTS ------------- // Iterate through all argv command line arguments, parsing out necessary flags for(i = 1; i < argc; i++) { // '-d' or '--daemon' flag: daemonize the server, and run it in the background if(strcmp("-d", argv[i]) == 0 || strcmp("--daemon", argv[i]) == 0) { // Set daemon flag to true, so we may daemonize later daemonized = 1; } // '-h' or '--help' flag: print help and usage for this server, then exit else if(strcmp("-h", argv[i]) == 0 || strcmp("--help", argv[i]) == 0) { // Print usage message fprintf(stdout, "usage: %s [-d | --daemon] [-h | --help] [-l | --lock lock_file] [-p | --port port] [-q | --queue queue_length] [-t | --threads thread_count]\n\n", SERVER_NAME); // Print out all available flags fprintf(stdout, "%s flags:\n", SERVER_NAME); fprintf(stdout, "\t-d | --daemon: daemonize - start server as a daemon, running it in the background\n"); fprintf(stdout, "\t-h | --help: help - print usage information and details about each flag the server accepts\n"); fprintf(stdout, "\t-l | --lock: lock_file - specify the location of the lock file utilized when the server is daemonized (default: %s)\n", LOCKFILE); fprintf(stdout, "\t-p | --port: port - specify an alternative port number to run the server (default: %s)\n", DEFAULT_PORT); fprintf(stdout, "\t-q | --queue: queue_length - specify the connection queue length for the incoming socket (default: %d)\n", QUEUE_LENGTH); fprintf(stdout, "\t-t | --threads: thread_count - specify the number of threads to generate (max number of clients) (default: %d)\n", NUM_THREADS); fprintf(stdout, "\n"); // Print out all available console commands via the common console_help() function console_help(); // Exit the server exit(0); } // '-l' or '--lock' flag: specify an alternate lock file location else if(strcmp("-l", argv[i]) == 0 || strcmp("--lock", argv[i]) == 0) { // Make sure that another argument exists, specifying the lockfile location if(argv[i+1] != NULL) { // Set lock file location as specified on the command line lock_location = argv[i+1]; i++; } else { // Print error and use default location if no lockfile was specified after the flag fprintf(stderr, "%s: %s no lockfile location specified, defaulting to %s\n", SERVER_NAME, ERROR_MSG, LOCKFILE); } } // '-p' or '--port' flag: specifies an alternative port number to run the server else if(strcmp("-p", argv[i]) == 0 || strcmp("--port", argv[i]) == 0) { // Make sure that another argument exists, specifying the port number if(argv[i+1] != NULL) { // Ensure this port is a valid integer if(validate_int(argv[i+1])) { // Set this port to be used if it's within the valid range, else use the default if(atoi(argv[i+1]) >= 0 && atoi(argv[i+1]) <= MAX_PORT) { port = argv[i+1]; i++; } else fprintf(stderr, "%s: %s port lies outside valid range (0-%d), defaulting to %s\n", SERVER_NAME, ERROR_MSG, MAX_PORT, DEFAULT_PORT); } else { // Print error and use default port if an invalid port number was specified fprintf(stderr, "%s: %s invalid port number specified, defaulting to %s\n", SERVER_NAME, ERROR_MSG, DEFAULT_PORT); } } else { // Print error and use default port if no port number was specified after the flag fprintf(stderr, "%s: %s no port number specified after flag, defaulting to %s\n", SERVER_NAME, ERROR_MSG, DEFAULT_PORT); } } // '-q' or '--queue' flag: specify the connection queue length else if(strcmp("-q", argv[i]) == 0 || strcmp("--queue", argv[i]) == 0) { // Make sure another argument exists, specifying the queue length if(argv[i+1] != NULL) { // Ensure this is a valid integer for queue length if(validate_int(argv[i+1])) { // Set connection queue length to the number specified on the command line, if it's a number more than 0, else use the default if(atoi(argv[i+1]) >= 1) { queue_length = atoi(argv[i+1]); i++; } else fprintf(stderr, "%s: %s cannot use negative or zero queue length, defaulting to length %d\n", SERVER_NAME, ERROR_MSG, QUEUE_LENGTH); } else { // Print error and use default queue length if an invalid number was specified fprintf(stderr, "%s: %s invalid queue length specified, defaulting to length %d\n", SERVER_NAME, ERROR_MSG, QUEUE_LENGTH); } } else { // Print error and use default queue length if no length was specified after the flag fprintf(stderr, "%s: %s no queue length specified after flag, default to length %d\n", SERVER_NAME, ERROR_MSG, QUEUE_LENGTH); } } // '-t' or '--threads' flag: specify the number of threads to generate in the thread pool else if(strcmp("-t", argv[i]) == 0 || strcmp("--threads", argv[i]) == 0) { // Make sure next argument exists, specifying the number of threads if(argv[i+1] != NULL) { // Ensure this number is a valid integer if(validate_int(argv[i+1])) { // Set number of threads to the number specified on the command line, if it's a number more than 0, else use the default if(atoi(argv[i+1]) >= 1) { num_threads = atoi(argv[i+1]); i++; } else fprintf(stderr, "%s: %s cannot use negative or zero threads, defaulting to %d threads\n", SERVER_NAME, ERROR_MSG, NUM_THREADS); } else { // Print error and use default number of threads if an invalid number was specified fprintf(stderr, "%s: %s invalid number of threads specified, defaulting to %d threads\n", SERVER_NAME, ERROR_MSG, NUM_THREADS); } } else { // Print error and use default number of threads if no count was specified after the flag fprintf(stderr, "%s: %s no thread count specified after flag, defaulting to %d threads\n", SERVER_NAME, ERROR_MSG, NUM_THREADS); } } else { // Else, an invalid flag or parameter was specified; print an error and exit fprintf(stderr, "%s: %s unknown parameter '%s' specified, please run '%s -h' for help and usage\n", SERVER_NAME, ERROR_MSG, argv[i], SERVER_NAME); exit(-1); } } //------------------------ OPEN SQLITE DATABASE ---------------- // Open database file, as specified in config header; check for success sqlite3_open(DB_FILE, &db); if(db == NULL) { // Print an error message and quit if database fails to open fprintf(stderr, "%s: %s sqlite: could not open database %s\n", SERVER_NAME, ERROR_MSG, DB_FILE); exit(-1); } // Create a query to truncate the files table in the database sprintf(query, "DELETE FROM files"); // Prepare, evaluate, and finalize SQLite query sqlite3_prepare_v2(db, query, strlen(query) + 1, &stmt, NULL); if(sqlite3_step(stmt) != SQLITE_DONE) { // On query failure, print an error and exit fprintf(stderr, "%s: %s sqlite: could not truncate files table\n", SERVER_NAME, ERROR_MSG); exit(-1); } sqlite3_finalize(stmt); //------------------------ INITIALIZE TCP SERVER --------------- // Clear the hints struct using memset to nullify it memset(&hints, 0, sizeof(hints)); // Set options for hints to use IPv4, a TCP connection, and the machine's current IP address hints.ai_family = AF_INET; // IPv4 hints.ai_socktype = SOCK_STREAM; // Reliable TCP connection hints.ai_flags = AI_PASSIVE; // Use my ip address // now populate our result addrinfo if((getaddrinfo(NULL, port, &hints, &result)) != 0) { // If getaddrinfo() fails, print an error and quit the program, since setup cannot continue. fprintf(stderr, "%s: %s getaddrinfo() call failed\n", SERVER_NAME, ERROR_MSG); exit(-1); } // Attempt to instantiate the local socket, using values set by getaddrinfo() if((loc_fd = socket(result->ai_family, result->ai_socktype, result->ai_protocol)) == -1) { // On socket creation failure, print an error and exit fprintf(stderr, "%s: %s local socket creation failed\n", SERVER_NAME, ERROR_MSG); exit(-1); } // Allow the system to free and re-bind the socket if it is already in use if(setsockopt(loc_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { // If setting a socket option fails, terminate the program after printing an error fprintf(stderr, "%s: %s failed to set socket option: SO_REUSEADDR\n", SERVER_NAME, ERROR_MSG); exit(-1); } // Attempt to bind the local socket if((bind(loc_fd, result->ai_addr, result->ai_addrlen)) == -1) { // If socket binding fails, it's typically one of two scenarios: // 1) Check if socket is on a privileged port, and permission is denied if(atoi(port) < PRIVILEGED_PORT) fprintf(stderr, "%s: %s failed to bind local socket (permission denied?)\n", SERVER_NAME, ERROR_MSG); // 2) Else, the socket is probably already bound else fprintf(stderr, "%s: %s failed to bind local socket (socket already in use?)\n", SERVER_NAME, ERROR_MSG); // Exit on failure exit(-1); } // Free the results struct, as it is no longer needed freeaddrinfo(result); // Begin listening on the local socket, and set connection queue length as defined above if((listen(loc_fd, queue_length)) == -1) { // Print error message if socket fails to begin listening fprintf(stderr, "%s: %s failed to begin listening on local socket\n", SERVER_NAME, ERROR_MSG); } //-------------------------- DAEMONIZATION ------------------ // If server is being daemonized, do so now. if(daemonized == 1) daemonize(); else { // Initialize a thread pool, using number of threads as defined earlier threadpool = thpool_init(num_threads); // Initialize the network thread to handle all incoming connections pthread_create(&net_thread, NULL, &tcp_listen, NULL); // Print out server information and ready message fprintf(stdout, "%s: %s server initialized [PID: %d] [port: %s] [queue: %d] [threads: %d]\n", SERVER_NAME, OK_MSG, getpid(), port, queue_length, num_threads); // If server is not being daemonized, use the default console interface fprintf(stdout, "%s: %s type 'stop' or hit Ctrl+C (SIGINT) to stop server\n", SERVER_NAME, INFO_MSG); } //------------------------- CONSOLE COMMAND --------------- // Loop continuously until 'stop' is provided on the console while(1) { // Read in user input, clean it up fgets(command, sizeof(command), stdin); clean_string((char *)&command); // 'clear' - Clear the console if(strcmp(command, "clear") == 0) system("clear"); // 'help' - Display the common console help menu else if(strcmp(command, "help") == 0) console_help(); // 'stat' - Print out server statistics else if(strcmp(command, "stat") == 0) print_stats(); // 'stop' - Stop the server, breaking this loop else if(strcmp(command, "stop") == 0) break; // Else, print console error stating command does not exist else fprintf(stderr, "%s: %s unknown console command '%s', type 'help' for console command help\n", SERVER_NAME, ERROR_MSG, command); } // Send SIGINT to the server so that it will gracefully terminate via signal handler kill(getpid(), SIGINT); }
// The function which handles all the heavy lifting for daemonization of the server void daemonize() { // Declare PID and SID to create a forked process, and detach from the parent pid_t pid, sid; // Create buffer to store PID in lockfile char pidstr[6]; // Check if we are already daemonized. If yes, return if(getppid() == 1) return; // Fork off the parent process, die on failure if((pid = fork()) < 0) { // Print an error to the console and die fprintf(stderr, "%s: %s failed to fork child process and daemonize\n", SERVER_NAME, ERROR_MSG); exit(-1); } // End the parent process, as it is no longer needed, but wait just a moment first to print any errors which occur below if(pid > 0) { usleep(250); exit(0); } // Now executing as child process. // Set the file mode mask umask(0); // Create a new SID for child process, die on failure if((sid = setsid()) < 0) { // Print an error to the console and die fprintf(stderr, "%s: %s failed to set new session for child process\n", SERVER_NAME, ERROR_MSG); exit(-1); } // Change current working directory to root, to prevent locking if(chdir("/") < 0) { fprintf(stderr, "%s: %s failed to change working directory\n", SERVER_NAME, ERROR_MSG); exit(-1); } // Open pidfile using the defined location if((pidfile = open(lock_location, O_RDWR|O_CREAT, 0600)) < 0) { fprintf(stderr, "%s: %s failed to open lock file (permission denied?)\n", SERVER_NAME, ERROR_MSG); exit(-1); } // Try to lock the pidfile if(lockf(pidfile, F_TLOCK, 0) == -1) { fprintf(stderr, "%s: %s failed to lock PID file (daemon already running?)\n", SERVER_NAME, ERROR_MSG); exit(-1); } // Format PID and store in string sprintf(pidstr, "%d\n", getpid()); // Write PID to lockfile write(pidfile, pidstr, strlen(pidstr)); // Print success message fprintf(stdout, "%s: %s daemonization complete [PID: %d] [lock: %s] [term: %s] [port: %s] [queue: %d] [threads: %d]\n", SERVER_NAME, OK_MSG, getpid(), lock_location, term, port, queue_length, num_threads); // Redirect standard streams to /dev/null freopen("/dev/null", "r", stdin); freopen("/dev/null", "w", stdout); freopen("/dev/null", "w", stderr); // When daemonizing, we must initialize the threadpool and listener thread here. // Initialize a thread pool, using number of threads as defined earlier threadpool = thpool_init(num_threads); // Initialize the network thread to handle all incoming connections pthread_create(&net_thread, NULL, &tcp_listen, NULL); // Loop and sleep infinitely until death. This is the end of the line for the main thread. while(1) sleep(60); }
int main(void) { _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); int width = 800, height = 600; GLFWwindow* window; glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); window = glfwCreateWindow(width, height, "cpu-voxels", NULL, NULL); if (!window) { glfwTerminate(); return 1; } glfwMakeContextCurrent(window); glfwSwapInterval(0); glfwSetKeyCallback(window, key_callback); glfwSetMouseButtonCallback(window, mouse_button_callback); glfwSetCursorPosCallback(window, mouse_move_callback); glfwSetKeyCallback(window, key_callback); vec3 eye = vec3_create(0.0f, 0.0f, VOXEL_BRICK_SIZE * 4); vec3 center = vec3f(0.0f); vec3 up = vec3_create(0.0, 1.0, 0.0 ); orbit_camera_init(eye, center, up); // TODO: handle resize int dw, dh; glfwGetFramebufferSize(window, &dw, &dh); int stride = 3; int total = dw*dh*stride; uint8_t *data = malloc(total); vec3 ro; //, rd; mat4 m4inverted, view; mat4 projection; mat4_perspective( projection, M_PI/4.0, (float)width/(float)height, 0.1, 1000.0 ); GLuint texture[1]; #ifdef ENABLE_THREADS screen_area areas[TOTAL_THREADS]; threadpool thpool = thpool_init(TOTAL_THREADS); #else screen_area areas[1]; #endif glGenTextures(1, texture); float start = glfwGetTime(); int fps = 0; voxel_brick my_first_brick = voxel_brick_create(); // TODO: make this work when the brick lb corner is not oriented at 0,0,0 voxel_brick_position(my_first_brick, vec3f(0.0f)); voxel_brick_fill(my_first_brick, &brick_fill); while (!glfwWindowShouldClose(window)) { if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) { orbit_camera_rotate(0, 0, -.1, 0); } if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) { orbit_camera_rotate(0, 0, .1, 0); } if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) { orbit_camera_rotate(0, 0, 0, .1); } if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) { orbit_camera_rotate(0, 0, 0, -.1); } glfwGetFramebufferSize(window, &width, &height); float now = glfwGetTime(); if (now - start > 1) { unsigned long long total_rays = (fps * width * height); printf("fps: %i (%f Mrays/s)@%ix%i - %i threads\n", fps, total_rays/1000000.0, width, height, TOTAL_THREADS); start = now; fps = 0; } fps++; orbit_camera_view(view); ro = mat4_get_eye(view); mat4_mul(m4inverted, projection, view); mat4_invert(m4inverted, m4inverted); // compute 3 points so that we can interpolate instead of unprojecting // on every point vec3 rda, rdb, planeYPosition, dcol, drow; vec3 t0 = vec3_create(0, 0, 0), tx = vec3_create(1, 0, 0), ty = vec3_create(0, 1, 0); vec4 viewport = { 0, 0, width, height }; rda = orbit_camera_unproject(t0, viewport, m4inverted); rdb = orbit_camera_unproject(tx, viewport, m4inverted); planeYPosition = orbit_camera_unproject(ty, viewport, m4inverted); dcol = planeYPosition - rda; drow = rdb - rda; int i=0, bh = height; #ifdef ENABLE_THREADS bh = (height/TOTAL_THREADS); for (i; i<TOTAL_THREADS; i++) { #endif areas[i].dcol = dcol; areas[i].drow = drow; areas[i].pos = planeYPosition; areas[i].ro = ro; areas[i].x = 0; areas[i].y = i*bh; areas[i].width = width; areas[i].height = areas[i].y + (int)(bh); areas[i].screen_height = (int)(height); areas[i].stride = stride; areas[i].data = data; areas[i].render_id = i; areas[i].brick = my_first_brick; #ifdef ENABLE_THREADS thpool_add_work(thpool, (void *)render_screen_area, (void *)(&areas[i])); } thpool_wait(thpool); #else render_screen_area((void *)(&areas[i])); #endif #ifdef RENDER glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_CULL_FACE); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glScalef(1.0f, -1.0f, 1.0f); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture[0]); glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glBegin(GL_QUADS); glTexCoord2f(0.0f, 0.0f); glVertex2f( -1, -1); glTexCoord2f(1.0f, 0.0f); glVertex2f( 1, -1); glTexCoord2f(1.0f, 1.0f); glVertex2f( 1, 1); glTexCoord2f(0.0f, 1.0f); glVertex2f( -1, 1); glEnd(); glfwSwapBuffers(window); glDeleteTextures(1, &texture[0]); #endif glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); }
obf_state_t * obf_init(enum mmap_e type, const char *dir, size_t secparam, size_t kappa, size_t nzs, size_t nthreads, size_t ncores, char *seed, uint64_t flags) { obf_state_t *s = NULL; if (secparam == 0 || kappa == 0 || nzs == 0) return NULL; s = calloc(1, sizeof(obf_state_t)); if (s == NULL) return NULL; s->secparam = secparam; s->type = type; s->dir = dir; s->nzs = nzs; s->flags = flags; s->randomizer = malloc(sizeof(fmpz_mat_t)); s->inverse = malloc(sizeof(fmpz_mat_t)); switch (s->type) { case MMAP_DUMMY: s->vtable = &dummy_vtable; break; case MMAP_CLT: s->vtable = &clt_vtable; break; case MMAP_GGHLITE: s->vtable = &gghlite_vtable; break; default: return NULL; } if (seed) { FILE *f; char dest[AES_SEED_BYTE_SIZE]; size_t n; if ((f = fopen(seed, "r")) == NULL) { fprintf(stderr, "unable to open seed file '%s'\n", seed); return NULL; } n = fread(dest, sizeof(*dest), AES_SEED_BYTE_SIZE, f); if (n != AES_SEED_BYTE_SIZE) { fprintf(stderr, "unable to read %d bytes of seed, only %ld bytes read\n", AES_SEED_BYTE_SIZE, n); fclose(f); return NULL; } fclose(f); if (s->flags & OBFUSCATOR_FLAG_VERBOSE) { fprintf(stderr, " Seed: "); for (int i = 0; i < AES_SEED_BYTE_SIZE; ++i) { fprintf(stderr, "%02x", dest[i]); } fprintf(stderr, "\n"); } aes_randinit_seedn(s->rand, dest, AES_SEED_BYTE_SIZE, NULL, 0); } else { (void) aes_randinit(s->rand); } if (nthreads == 0) nthreads = ncores; s->thpool = thpool_init(nthreads); s->nthreads = nthreads; /* Generate dedicated randomness for threads */ s->rands = calloc(nthreads, sizeof(aes_randstate_t)); for (uint64_t i = 0; i < nthreads; ++i) { unsigned char *buf; size_t nbits = 128, nbytes; buf = random_aes(s->rand, nbits, &nbytes); aes_randinit_seedn(s->rands[i], (char *) buf, nbytes, NULL, 0); free(buf); } if (s->flags & OBFUSCATOR_FLAG_VERBOSE) { fprintf(stderr, " # Threads: %lu\n", nthreads); fprintf(stderr, " # Cores: %lu\n", ncores); if (s->flags & OBFUSCATOR_FLAG_DUAL_INPUT_BP) fprintf(stderr, " Using dual input branching programs\n"); if (s->flags & OBFUSCATOR_FLAG_NO_RANDOMIZATION) fprintf(stderr, " Not randomizing branching programs\n"); } s->mmap = malloc(s->vtable->sk->size); s->vtable->sk->init(s->mmap, secparam, kappa, nzs, NULL, 0, ncores, s->rand, s->flags & OBFUSCATOR_FLAG_VERBOSE); { FILE *fp = open_file(dir, "params", "w+b"); s->vtable->pp->fwrite(s->vtable->sk->pp(s->mmap), fp); fclose(fp); } return s; }
void cppadcg_thpool_prepare() { if(cppadcg_pool == NULL) { cppadcg_pool = thpool_init(cppadcg_pool_n_threads); } }