Advertisement
STANAANDREY

pthreads cnt lines

Nov 22nd, 2024
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.25 KB | None | 0 0
  1. #define _GNU_SOURCE
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <pthread.h>
  5. #include <string.h>
  6. #include <sched.h>
  7.  
  8. #define LINE_SIZE (1 << 12)
  9.  
  10. static char target;
  11. void *routine(void *arg) {
  12.     char *line = (char*)arg;
  13.     int cnt = 0;
  14.     for (int i = 0; line[i]; i++) {
  15.         if (line[i] == target) {
  16.             cnt++;
  17.         }
  18.     }
  19.     printf("cnt=%d\n", cnt);
  20.     return NULL;
  21. }
  22.  
  23. int main(int argc, char *argv[]) {
  24.     if (argc != 2) {
  25.         fprintf(stderr, "WRONG USAGE!\n");
  26.         exit(1);
  27.     }
  28.     target = argv[1][0];
  29.  
  30.     cpu_set_t cpuset;
  31.     CPU_ZERO(&cpuset);
  32.     CPU_SET(0, &cpuset);
  33.  
  34.     pthread_attr_t attr;
  35.     pthread_attr_init(&attr);
  36.     pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpuset);
  37.  
  38.     char line[LINE_SIZE];
  39.     while (fgets(line, LINE_SIZE, stdin)) {
  40.         pthread_t thread;
  41.         int r = 0;
  42.         if ((r = pthread_create(&thread, &attr, routine, line)) != 0) {
  43.             fprintf(stderr, "pthread_create: %s\n", strerror(r));
  44.             exit(1);
  45.         }
  46.  
  47.         if ((r = pthread_join(thread, NULL)) != 0) {
  48.             fprintf(stderr, "pthread_join: %s\n", strerror(r));
  49.             exit(1);
  50.         }
  51.     }
  52.     pthread_attr_destroy(&attr);
  53.    
  54.     return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement