EXTREMEXPLOIT

Monitors

Mar 21st, 2021 (edited)
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.69 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <semaphore.h>
  3. #include <pthread.h>
  4. #include <fcntl.h>
  5. #include <stdlib.h>
  6. #include <unistd.h>
  7. #include <wait.h>
  8. #include <string.h>
  9. #include <sys/stat.h>
  10. #include <sys/shm.h>
  11. #include <stdbool.h>
  12.  
  13. #define NTHREADS 50
  14. #define NSUMS 100
  15.  
  16. int SUM[2] = {0, 0};
  17. pthread_t threadsID[NTHREADS];
  18.  
  19. bool isBusy1, isBusy2;
  20. pthread_mutex_t Lock1, Lock2;
  21. pthread_cond_t Condition1, Condition2;
  22.  
  23. void* ThreadFunction1(){
  24.     for (int i=0; i<NSUMS; i++)
  25.     {
  26.         pthread_mutex_lock(&Lock1);
  27.         while(isBusy1) pthread_cond_wait(&Condition1, &Lock1);
  28.         isBusy1 = true;
  29.         SUM[0]++;
  30.         isBusy1 = false;
  31.         pthread_cond_signal(&Condition1);
  32.         pthread_mutex_unlock(&Lock1);
  33.     }
  34.     return NULL;
  35. }
  36.  
  37. void* ThreadFunction2(){
  38.     for (int i=0; i<NSUMS; i++)
  39.     {
  40.         pthread_mutex_lock(&Lock2);
  41.         while(isBusy2) pthread_cond_wait(&Condition2, &Lock2);
  42.         isBusy2 = true;
  43.         SUM[1]++;
  44.         isBusy2 = false;
  45.         pthread_cond_signal(&Condition2);
  46.         pthread_mutex_unlock(&Lock2);
  47.     }
  48.     return NULL;
  49. }
  50.  
  51. int main()
  52. {
  53.     pthread_mutex_init(&Lock1, NULL); pthread_mutex_init(&Lock2, NULL);
  54.     pthread_cond_init(&Condition1, NULL); pthread_cond_init(&Condition2, NULL);
  55.     isBusy1 = false; isBusy2 = false;
  56.     for (int i=0; i<NTHREADS; i++){
  57.         if (i%2 == 0) pthread_create(&threadsID[i], NULL, ThreadFunction1,NULL);
  58.         else pthread_create(&threadsID[i], NULL, ThreadFunction2, NULL);
  59.     }
  60.  
  61.     for (int i=0; i<NTHREADS; i++) pthread_join(threadsID[i], NULL);
  62.  
  63.     printf("SUM = {%d, %d}\n", SUM[0], SUM[1]);
  64.     printf("Total Sum = %d\n", SUM[0]+SUM[1]);
  65.  
  66.     return 0;
  67. }
Add Comment
Please, Sign In to add comment