EXTREMEXPLOIT

Threads Barrier + Semaphores

Mar 17th, 2021 (edited)
645
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.75 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <unistd.h>
  4. #include <semaphore.h>
  5.  
  6. #define NTHREADS 100
  7. #define BARRIER_SIZE 25 // Número necesarios de threads esperando para levantar la barrera.
  8.  
  9. int K = 0;
  10. sem_t Semaphore;
  11.  
  12. void* doSomething(){
  13.     sem_wait(&Semaphore);
  14.     K += 1; // Critical Region.
  15.     sem_post(&Semaphore);
  16.  
  17.     return NULL;
  18. }
  19.  
  20. int main() {
  21.     pthread_t threadsID[NTHREADS];
  22.  
  23.     sem_init(&Semaphore, 0, BARRIER_SIZE); // Dirección de Memoria, 0 indica uso en en threads y el valor del semáforo.
  24.  
  25.     for (int i=0; i<NTHREADS; i++) { pthread_create(&threadsID[i], NULL, doSomething, NULL); }
  26.  
  27.     for (int i=0; i<NTHREADS; i++){ pthread_join(threadsID[i], NULL); }
  28.  
  29.     sem_destroy(&Semaphore);
  30.  
  31.     return 0;
  32. }
  33.  
Add Comment
Please, Sign In to add comment