wa12rior

C semaphore example with pthread library

Apr 13th, 2021
649
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <time.h>
  3. #include <math.h>
  4. #include <unistd.h>
  5. #include <stdlib.h>
  6. #include <pthread.h>
  7. #include <semaphore.h>
  8.  
  9.  
  10. #define ILOSC 1
  11. #define liczba_watkow 3
  12. #define wartosc_semafora 1
  13.  
  14. float t[liczba_watkow];
  15.  
  16. sem_t semafor;
  17.  
  18. void* p (void* k) { // funkcja watku (watek)
  19.          long nr=(long)k;
  20.          int l,i;
  21.  
  22.          for (i=0;i<ILOSC;i++) {
  23.          l = rand()%10;
  24.          sem_wait(&semafor);
  25.          t[nr-1] = l;
  26.          sem_post(&semafor);
  27.                  printf("watek %ld wylosowal %d \n",nr,l);fflush(stdout);
  28.  
  29.          }
  30.  
  31.  
  32. return 0;
  33. }
  34.  
  35. int main(int arg, char **argv) {
  36.  
  37. sem_init(&semafor, 0, wartosc_semafora);
  38. pthread_t w[liczba_watkow];
  39. long i=0;
  40. float suma;
  41.  
  42.  
  43. srand(time(0));
  44.  
  45. for (i=1;i<=liczba_watkow;i++)
  46.     pthread_create(&w[i-1],0,p,(void*)i);
  47.  
  48.  
  49. for (i=0;i<liczba_watkow;i++)
  50.     pthread_join(w[i],0);
  51. // oblicza wartości srednie
  52.  
  53. for (i=0;i<ILOSC;i++) {
  54. suma=0;
  55.  
  56. for (i=0;i<liczba_watkow;i++) suma+= t[i];
  57.  
  58. printf("\nsrednia = %f\n",suma/liczba_watkow);
  59.  
  60. }
  61.  
  62.  
  63. return 0;
  64.  
  65. }
  66.  
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×