Advertisement
STANAANDREY

pthread cnt lines mtx

Nov 27th, 2024
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.89 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. int n;
  11.  
  12. pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
  13. int totalCnt = 0;
  14.  
  15. static char target;
  16. void *routine(void *arg) {
  17.     char *line = (char*)arg;
  18.     int cnt = 0, r = 0;
  19.     for (int i = 0; line[i]; i++) {
  20.         if (line[i] == target) {
  21.             cnt++;
  22.         }
  23.     }
  24.     if ((r = pthread_mutex_lock(&mtx)) != 0) {
  25.         fprintf(stderr, "pthread_mutex_lock: %s\n", strerror(r));
  26.         pthread_exit(NULL);
  27.     }
  28.     totalCnt += cnt;
  29.     if ((r = pthread_mutex_unlock(&mtx)) != 0) {
  30.         fprintf(stderr, "pthread_mutex_unlock: %s\n", strerror(r));
  31.         pthread_exit(NULL);
  32.     }
  33.    
  34.     return NULL;
  35. }
  36.  
  37. int main(int argc, char *argv[]) {
  38.     if (argc != 2) {
  39.         fprintf(stderr, "WRONG USAGE!\n");
  40.         exit(1);
  41.     }
  42.     target = argv[1][0];
  43.  
  44.     cpu_set_t cpuset;
  45.     CPU_ZERO(&cpuset);
  46.     CPU_SET(0, &cpuset);
  47.  
  48.     pthread_attr_t attr;
  49.     pthread_attr_init(&attr);
  50.     pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpuset);
  51.  
  52.     scanf("%d", &n);
  53.     getchar();
  54.  
  55.     char line[n][LINE_SIZE];
  56.     for (int i = 0; i < n; i++) {
  57.         fgets(line[i], LINE_SIZE, stdin);
  58.     }
  59.  
  60.     pthread_t thread[n];
  61.     int r = 0;
  62.     pthread_mutex_init(&mtx, NULL);
  63.     for (int i = 0; i < n; i++) {
  64.         if ((r = pthread_create(&thread[i], &attr, routine, line[i])) != 0) {
  65.             fprintf(stderr, "pthread_create: %s\n", strerror(r));
  66.             exit(1);
  67.         }
  68.     }
  69.     for (int i = 0; i < n; i++) {
  70.         if ((r = pthread_join(thread[i], NULL)) != 0) {
  71.             fprintf(stderr, "pthread_join: %s\n", strerror(r));
  72.             exit(1);
  73.         }
  74.     }
  75.     pthread_attr_destroy(&attr);
  76.     pthread_mutex_destroy(&mtx);
  77.     printf("%d\n", totalCnt);
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement