EXTREMEXPLOIT

Semaphore using Monitors (POSIX)

Mar 22nd, 2021 (edited)
595
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.10 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <semaphore.h>
  3. #include <pthread.h>
  4. #include <stdlib.h>
  5. #include <unistd.h>
  6. #include <wait.h>
  7. #include <string.h>
  8. #include <stdbool.h>
  9.  
  10. #define SEMAPHORE_VALUE 5
  11. #define NTHREADS 10000
  12.  
  13. int K = 0;
  14. pthread_t threadsID[NTHREADS];
  15.  
  16. typedef struct SemStruct{
  17.   int AvaliableThreads;
  18.   pthread_mutex_t Lock; pthread_cond_t Condition;
  19. } Semaphore;
  20.  
  21. void InitSemaphore(Semaphore* CurrentSemaphore, int n){
  22.     CurrentSemaphore->AvaliableThreads = n;
  23.     pthread_mutex_init(&CurrentSemaphore->Lock, NULL);
  24.     pthread_cond_init(&CurrentSemaphore->Condition, NULL);
  25. }
  26.  
  27. void Wait(Semaphore* CurrentSemaphore){
  28.     pthread_mutex_lock(&CurrentSemaphore->Lock);
  29.     while(CurrentSemaphore->AvaliableThreads == 0) pthread_cond_wait(&CurrentSemaphore->Condition, &CurrentSemaphore->Lock);
  30.     CurrentSemaphore->AvaliableThreads--;
  31.     pthread_mutex_unlock(&CurrentSemaphore->Lock);
  32. }
  33.  
  34. void Signal(Semaphore* CurrentSemaphore){
  35.     pthread_mutex_lock(&CurrentSemaphore->Lock);
  36.     pthread_cond_signal(&CurrentSemaphore->Condition);
  37.     CurrentSemaphore->AvaliableThreads++;
  38.     pthread_mutex_unlock(&CurrentSemaphore->Lock);
  39. }
  40.  
  41. int Factorial(int N){
  42.     if (N <= 1) return N;
  43.     else return N*Factorial(N-1);
  44. }
  45.  
  46. Semaphore* MySemaphore;
  47.  
  48. void* ThreadFunction(){
  49.     Wait(MySemaphore);
  50.  
  51.     printf("Current Number of Threads: %d \n", SEMAPHORE_VALUE - MySemaphore->AvaliableThreads);
  52.     int N1, N2, N3, N4, N5;
  53.     N1 = 100%(K+1) + 1; N2 = 100%(K+2) + 1; N3 = 100%(K+3) + 1; N4 = 100%(K+4) + 1; N5 = 100%(K+5) + 1;
  54.     N1 = Factorial(N1); N2 = Factorial(N2); N3 = Factorial(N3); N4 = Factorial(N4); N5 = Factorial(N5);
  55.     int N[5] = {N1, N2, N3, N4, N5};
  56.     K += N[rand()%5];
  57.  
  58.     Signal(MySemaphore);
  59.     return NULL;
  60. }
  61.  
  62. int main() {
  63.     MySemaphore = malloc(sizeof(Semaphore));
  64.     InitSemaphore(MySemaphore, SEMAPHORE_VALUE);
  65.  
  66.     for (int i=0; i<NTHREADS; i++) pthread_create(&threadsID[i], NULL, ThreadFunction, NULL);
  67.     for (int i=0; i<NTHREADS; i++) pthread_join(threadsID[i], NULL);
  68.  
  69.     printf("--------> END OF THREADS <--------\n");
  70.  
  71.     return 0;
  72. }
  73.  
Add Comment
Please, Sign In to add comment