Advertisement
ceva_megamind

rand in threads

Dec 15th, 2021 (edited)
711
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.99 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. enum
  6. {
  7.     COUNT = 10000,
  8.     BASIS = 10,
  9.     RAND_RANGE = 10
  10. };
  11.  
  12. pthread_mutex_t m[COUNT];
  13. int count, iter_count, nproc;
  14.  
  15. void
  16. operation(int *data, int ind1, int ind2, int value)
  17. {
  18.     if (ind1 != ind2) {
  19.         int tmp1 = data[ind1] - value;
  20.         int tmp2 = data[ind2] + value;
  21.         data[ind1] = tmp1;
  22.         data[ind2] = tmp2;
  23.     }
  24. }
  25.  
  26. void *
  27. func(void *ptrr)
  28. {
  29.     int **ptr = (int **) ptrr;
  30.     srand(*ptr[1]); // or nothing
  31.     for (int i = 0; i < iter_count; i++) {
  32.         int ind1 = rand() % count, //or rand_r(ptr[1])
  33.         ind2 = rand() % count, //or rand_r(ptr[1])
  34.         value = rand() % RAND_RANGE; //or rand_r(ptr[1])
  35.         pthread_mutex_lock(&m[ind1]);
  36.         if (ind1 != ind2) pthread_mutex_lock(&m[ind2]);
  37.          operation(ptr[0], ind1, ind2, value);
  38.         pthread_mutex_unlock(&m[ind1]);
  39.         if (ind1 != ind2) pthread_mutex_unlock(&m[ind2]);
  40.     }
  41.     return NULL;
  42. }
  43.  
  44. int
  45. main(int argc, char *argv[])
  46. {
  47.     int gprn[COUNT];
  48.     count = strtol(argv[1], NULL, BASIS);
  49.     nproc = strtol(argv[3], NULL, BASIS);
  50.     iter_count = strtol(argv[4], NULL, BASIS);
  51.     for (int i = 0; i < nproc; ++i) {
  52.         gprn[i] = strtol(argv[5 + i], NULL, BASIS);
  53.     }
  54.  
  55.     int data[COUNT];
  56.     for (int i = 0; i < count; ++i) {
  57.         scanf("%d", &data[i]);
  58.     }
  59.     for (int i = 0; i < count; i++) {
  60.         pthread_mutex_init(&m[i], NULL);
  61.         pthread_mutex_unlock(&m[i]);
  62.     }
  63.  
  64.     int **ptr = calloc(2, sizeof(*ptr));
  65.     ptr[0] = data;
  66.     ptr[1] = calloc(1, sizeof(*ptr[1]));
  67.     pthread_t ids[COUNT];
  68.     for (int i = 0; i < nproc; ++i) {
  69.         *ptr[1] = gprn[i];
  70.         pthread_create(&ids[i], NULL, func, ptr);
  71.     }
  72.     for (int i = 0; i < nproc; i++) {
  73.         pthread_join(ids[i], NULL);
  74.     }
  75.     for (int i = 0; i < count; i++) {
  76.         printf("%d\n", data[i]); fflush(stdout);
  77.     }
  78.     free(ptr[1]);free(ptr);
  79.     return 0;
  80. }                  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement