Advertisement
STANAANDREY

pthread interval template

Dec 12th, 2024
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.23 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <pthread.h>
  5.  
  6. typedef struct {
  7.     int a, b;
  8. } ThArg;
  9.  
  10. int a, b, n;
  11.  
  12. void *troutine(void *arg) {
  13.     ThArg *thArg = (ThArg*)arg;
  14.     printf("Processed [%d %d]\n", thArg->a, thArg->b);
  15.     return NULL;
  16. }
  17.  
  18. void *zalloc(int nmemb, int sz) {
  19.     void *p = calloc(nmemb, sz);
  20.     if (!p) {
  21.         perror("");
  22.         exit(1);
  23.     }
  24.     return p;
  25. }
  26.  
  27. int main(void) {
  28.     scanf("%d%d%d", &a, &b, &n);
  29.  
  30.     int numsPerTh = (b - a + 1) / n;
  31.     pthread_t *threads = (pthread_t*)zalloc(n, sizeof(pthread_t));
  32.     ThArg *thArgs = (ThArg*)zalloc(n, sizeof(ThArg));
  33.  
  34.     for (int r, i = 0; i < n; i++) {
  35.         thArgs[i].a = a + i * numsPerTh;
  36.         thArgs[i].b = (i == n - 1) ? b : thArgs[i].a + numsPerTh - 1;
  37.         if ((r = pthread_create(&threads[i], NULL, troutine, &thArgs[i]))) {
  38.             fprintf(stderr, "pthread_create error: %s", strerror(r));
  39.             exit(-1);
  40.         }
  41.     }
  42.  
  43.     for (int r, i = 0; i < n; i++) {
  44.         if ((r = pthread_join(threads[i], NULL))) {
  45.             fprintf(stderr, "pthread_join error: %s", strerror(r));
  46.             exit(-1);
  47.         }
  48.     }
  49.  
  50.     free(thArgs);
  51.     free(threads);
  52.  
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement