Advertisement
tftrgi11

Untitled

Jun 19th, 2020
1,504
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.76 KB | None | 0 0
  1. #include <stdint.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <getopt.h>
  5. #include <stdbool.h>
  6. #include <sys/time.h>
  7.  
  8. #include <pthread.h>
  9.  
  10. int begin = 2;
  11. int end = 0;
  12. int mod = 1;
  13.  
  14. pthread_mutex_t mut1 = PTHREAD_MUTEX_INITIALIZER;
  15. pthread_mutex_t mut2 = PTHREAD_MUTEX_INITIALIZER;
  16.  
  17.  
  18. void* Fact1(void *args) {
  19.   int a = -1;
  20.   int b = 1;
  21.   int m = mod;
  22.   printf("Fact1 1st lock\n");
  23.   pthread_mutex_lock(&mut1);
  24.   while (begin < 50000)
  25.   {
  26.       begin++;
  27.   }
  28.   printf("Fact1 2nd lock\n");
  29.   pthread_mutex_lock(&mut2);
  30.   m = begin + end;
  31.   printf("Fact1 2nd unlock\n");
  32.   pthread_mutex_unlock(&mut2);
  33.   printf("Fact1 1st unlock\n");
  34.   pthread_mutex_unlock(&mut1);
  35.   int prod = 1;
  36.  
  37.   return 0;
  38. }
  39.  
  40. void* Fact2(void *args) {
  41.   int a = -1;
  42.   int b = 1;
  43.   int m = mod;
  44.   printf("Fact2 1st lock\n");
  45.   pthread_mutex_lock(&mut2);
  46.   while (end < 50000)
  47.   {
  48.       end++;
  49.   }
  50.   printf("Fact1 2nd lock\n");
  51.   pthread_mutex_lock(&mut1);
  52.   m = begin + end;
  53.   printf("Fact1 2nd unlock\n");
  54.   pthread_mutex_unlock(&mut1);
  55.   printf("Fact1 1st unlock\n");
  56.   pthread_mutex_unlock(&mut2);
  57.  
  58.   return 0;
  59. }
  60.  
  61.  
  62. int main() {
  63.   int pnum = 2;
  64.   pthread_t threads[pnum];
  65.   int *array = malloc(sizeof(int) * 1);
  66.  
  67.  
  68.     if (pthread_create(&threads[0], NULL, Fact1, (void *)&array)) {
  69.       printf("Error: pthread_create failed!\n");
  70.       return 1;
  71.     }
  72.     if (pthread_create(&threads[1], NULL, Fact2, (void *)&array)) {
  73.       printf("Error: pthread_create failed!\n");
  74.       return 1;
  75.     }
  76.  
  77.   int total_prod = 1;
  78.   for (uint32_t i = 0; i < pnum; i++) {
  79.     int prod = 0;
  80.     pthread_join(threads[i], (void **)&prod);
  81.     total_prod = (total_prod * prod) % mod;
  82.   }
  83.  
  84.   free(array);
  85.   printf("Total: %d\n", total_prod);
  86.   return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement