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); }
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); }
// Function called by network thread, used to separate the TCP listener from the console thread void *tcp_listen() { // Set up p2p_t struct, to pass variables into the thread function p2p_t params; // Create output buffer, in case the base server must communicate directly to the client char out[512] = { '\0' }; // Loop infinitely until Ctrl+C SIGINT is caught by the signal handler while(1) { // Attempt to accept incoming connections using the incoming socket if((inc_fd = accept(loc_fd, (struct sockaddr *)&inc_addr, &inc_len)) == -1) { // Print an error message and quit if server cannot accept connections fprintf(stderr, "%s: %s failed to accept incoming connections\n", SERVER_NAME, ERROR_MSG); return (void *)-1; } else { // If a connection is accepted, continue routines. // Capture client's IP address for logging. inet_ntop(inc_addr.ss_family, get_in_addr((struct sockaddr *)&inc_addr), clientaddr, sizeof(clientaddr)); // Print message when connection is received, and increment client counter fprintf(stdout, "%s: %s client connected from %s [fd: %d] [users: %d/%d]\n", SERVER_NAME, OK_MSG, clientaddr, inc_fd, client_count(1), num_threads); // If client count reaches the utilization threshold, print a warning if(((double)client_count(0) >= ((double)num_threads * TP_UTIL)) && (client_count(0) <= num_threads)) { // Print warning to server console, alter wording slightly if utilization is maxed out if(client_count(0) == num_threads) fprintf(stdout, "%s: %s thread pool exhausted [users: %d/%d]\n", SERVER_NAME, WARN_MSG, client_count(0), num_threads); else fprintf(stdout, "%s: %s thread pool nearing exhaustion [users: %d/%d]\n", SERVER_NAME, WARN_MSG, client_count(0), num_threads); } // If client count exceeds the number of threads in the pool, print an error else if((client_count(0)) > num_threads) { // Print error to console fprintf(stderr, "%s: %s thread pool over-exhausted [users: %d/%d]\n", SERVER_NAME, ERROR_MSG, client_count(0), num_threads); // Generate message to send to client sprintf(out, "%s: %s server has currently reached maximum user capacity, please wait\n", SERVER_NAME, USER_MSG); send_msg(inc_fd, out); } // Store user's file descriptor and IP address in the params struct params.fd = inc_fd; strcpy(params.ipaddr, clientaddr); // On client connection, add work to the threadpool, pass in params struct thpool_add_work(threadpool, &p2p, (void*)¶ms); } } }
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; }
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; }
/*** * Add a connected peer to the swarm * NOTE: We should already have a connection to the peer * @param context the SwarmContext * @param peer the connected peer * @returns true(1) on success, false(0) otherwise */ int libp2p_swarm_add_peer(struct SwarmContext* context, struct Libp2pPeer* peer) { // spin off a thread for this peer struct SwarmSession* swarm_session = (struct SwarmSession*) malloc(sizeof(struct SwarmSession)); swarm_session->session_context = peer->sessionContext; swarm_session->swarm_context = context; if (thpool_add_work(context->thread_pool, libp2p_swarm_listen, swarm_session) < 0) { libp2p_logger_error("swarm", "Unable to fire up thread for peer %s\n", libp2p_peer_id_to_string(peer)); return 0; } libp2p_logger_info("swarm", "add_connection: added connection for peer %s.\n", libp2p_peer_id_to_string(peer)); return 1; }
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; }
/** * add an incoming connection * @param context the SwarmContext * @param file_descriptor the incoming file descriptor of the connection * @param ip the incoming ip (ipv4 format) * @param port the incoming port * @return true(1) on success, false(0) otherwise */ int libp2p_swarm_add_connection(struct SwarmContext* context, int file_descriptor, int ip, int port ) { // build a session context struct SessionContext* session = libp2p_session_context_new(); if (session == NULL) { libp2p_logger_error("swarm", "Unable to allocate SessionContext. Out of memory?\n"); return 0; } session->datastore = context->datastore; session->filestore = context->filestore; // convert IP address to text session->host = malloc(INET_ADDRSTRLEN); if (session->host == NULL) { // we are out of memory free(session->host); return 0; } if (inet_ntop(AF_INET, &ip, session->host, INET_ADDRSTRLEN) == NULL) { free(session->host); session->host = NULL; session->port = 0; return 0; } session->port = port; session->insecure_stream = libp2p_net_connection_new(file_descriptor, session->host, session->port, session); session->default_stream = session->insecure_stream; struct SwarmSession* swarm_session = (struct SwarmSession*) malloc(sizeof(struct SwarmSession)); swarm_session->session_context = session; swarm_session->swarm_context = context; if (thpool_add_work(context->thread_pool, libp2p_swarm_listen, swarm_session) < 0) { libp2p_logger_error("swarm", "Unable to fire up thread for connection %d\n", file_descriptor); return 0; } libp2p_logger_info("swarm", "add_connection: added connection %d.\n", file_descriptor); return 1; }
static void add_work(obf_state_t *s, fmpz_mat_t *mats, mmap_enc_mat_t **enc_mats, int **pows, long c, long i, long j, char *tag) { fmpz_t *plaintext; mmap_enc *enc; struct encode_elem_s *args; plaintext = malloc(sizeof(fmpz_t)); args = malloc(sizeof(struct encode_elem_s)); fmpz_init_set(*plaintext, fmpz_mat_entry(mats[c], i, j)); enc = enc_mats[c][0]->m[i][j]; args->group = pows[c]; args->n = 1; args->plaintext = plaintext; args->vtable = s->vtable; args->sk = s->mmap; args->enc = enc; args->rand = &s->rand; thpool_add_work(s->thpool, thpool_encode_elem, (void *) args, tag); }
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; }
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); }