fork download
  1. /************* korzystanie z semaforów ******************************
  2.  
  3. deklaracje w pliku semaphore.h
  4.  
  5.  
  6. sem_t - typ semaforowy
  7. sem_init(sem_t* s,0,wartość_semafora) - inicjowanie wartością początkową semafora
  8. sem_post(sem_t* s) - operacja signal
  9. sem_wait(sem_t* s) - operacja wait
  10.  
  11.  
  12.  
  13. **************************************************************/
  14.  
  15.  
  16. /************* korzystanie z mutexu ******************************
  17.  
  18.  
  19. ptheread_mutex_t - typ mutexowy
  20.  
  21. pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER - inicjowanie (mutex otwarty) (domyślna inicjalizacja)
  22. pthread_mutex_lock(pthread_mutex* m) - zamknięcie mutexu
  23. pthread_mutex_unlock(pthread_mutex* m) - otwarcie mutexu
  24.  
  25. uwaga:
  26. - operacja pthread_mutex_lock blokuje wątek gdy mutex jest zamkniety
  27. - operacja pthread_mutex_unlock jest niezdefiniowana gdy mutex jest otwarty
  28.  
  29.  
  30. **************************************************************/
  31.  
  32.  
  33. #include <stdio.h>
  34. #include <unistd.h>
  35. #include <stdlib.h>
  36. #include <pthread.h>
  37. #include <semaphore.h>
  38.  
  39. int x;
  40. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  41. #define iter 10
  42.  
  43. void* p (void* l) { // funkcja watku (watek)
  44. int i;
  45.  
  46. for (i=0;i<iter;i++) {
  47. pthread_mutex_lock(&mutex);
  48. x=i;
  49. pthread_mutex_unlock(&mutex);
  50. }
  51.  
  52.  
  53.  
  54. return 0;
  55. }
  56.  
  57.  
  58. void* q (void* l) { // funkcja watku (watek)
  59.  
  60. int i;
  61.  
  62. for (i=0;i<iter;i++) {
  63. pthread_mutex_lock(&mutex);
  64.  
  65. printf("x=%d\n",x);
  66. pthread_mutex_unlock(&mutex);
  67. }
  68.  
  69.  
  70. return 0;
  71. }
  72.  
  73.  
  74.  
  75. int main () {
  76. pthread_t w1,w2;
  77.  
  78.  
  79. pthread_create(&w1, 0, p,0); // tworzy nowy watek
  80. pthread_create(&w2, 0, q,0); // tworzy nowy watek
  81.  
  82.  
  83.  
  84.  
  85.  
  86.  
  87.  
  88.  
  89.  
  90. pthread_join(w1,0); // czeka na zakonczenie watku 1
  91. pthread_join(w2,0);
  92.  
  93.  
  94.  
  95.  
  96. return 0;
  97. }
  98.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
x=0
x=0
x=0
x=0
x=0
x=0
x=0
x=0
x=0
x=0