Advertisement
EXTREMEXPLOIT

Threads Barrier + Monitor

Mar 17th, 2021
599
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.87 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <unistd.h>
  4.  
  5. #define NTHREADS 100
  6. #define BARRIER_SIZE 25 // Número necesarios de threads esperando para levantar la barrera.
  7.  
  8. int K = 0;
  9. int readyThreads = 0;
  10.  
  11. pthread_cond_t isReady;
  12. pthread_mutex_t Lock;
  13.  
  14. void* doSomething(){
  15.     pthread_mutex_lock(&Lock);
  16.     while(readyThreads < BARRIER_SIZE) pthread_cond_wait(&isReady, &Lock);
  17.     K += 1; // Critical Region.
  18.     pthread_cond_broadcast(&isReady);
  19.     pthread_mutex_unlock(&Lock);
  20.  
  21.     return NULL;
  22. }
  23.  
  24. int main() {
  25.     pthread_t threadsID[NTHREADS];
  26.     pthread_mutex_init(&Lock, NULL);
  27.     pthread_cond_init(&isReady, NULL);
  28.  
  29.     for (int i=0; i<NTHREADS; i++) {
  30.         readyThreads++;
  31.         pthread_create(&threadsID[i], NULL, doSomething, NULL);
  32.     }
  33.  
  34.     for (int i=0; i<NTHREADS; i++){ pthread_join(threadsID[i], NULL); }
  35.  
  36.     return 0;
  37. }
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement