example02.lc 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include "unpthread.h"## 1 ##src/threads/example02.c##
  2. #define NLOOP 5000## 2 ##src/threads/example02.c##
  3. int counter; /* this is incremented by the threads */## 3 ##src/threads/example02.c##
  4. pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;## 4 ##src/threads/example02.c##
  5. void *doit(void *);## 5 ##src/threads/example02.c##
  6. int## 6 ##src/threads/example02.c##
  7. main(int argc, char **argv)## 7 ##src/threads/example02.c##
  8. {## 8 ##src/threads/example02.c##
  9. pthread_t tidA, tidB;## 9 ##src/threads/example02.c##
  10. Pthread_create(&tidA, NULL, &doit, NULL);## 10 ##src/threads/example02.c##
  11. Pthread_create(&tidB, NULL, &doit, NULL);## 11 ##src/threads/example02.c##
  12. /* 4wait for both threads to terminate */## 12 ##src/threads/example02.c##
  13. Pthread_join(tidA, NULL);## 13 ##src/threads/example02.c##
  14. Pthread_join(tidB, NULL);## 14 ##src/threads/example02.c##
  15. exit(0);## 15 ##src/threads/example02.c##
  16. }## 16 ##src/threads/example02.c##
  17. void *## 17 ##src/threads/example02.c##
  18. doit(void *vptr)## 18 ##src/threads/example02.c##
  19. {## 19 ##src/threads/example02.c##
  20. int i, val;## 20 ##src/threads/example02.c##
  21. /* ## 21 ##src/threads/example02.c##
  22. * Each thread fetches, prints, and increments the counter NLOOP times.## 22 ##src/threads/example02.c##
  23. * The value of the counter should increase monotonically.## 23 ##src/threads/example02.c##
  24. */## 24 ##src/threads/example02.c##
  25. for (i = 0; i < NLOOP; i++) {## 25 ##src/threads/example02.c##
  26. Pthread_mutex_lock(&counter_mutex);## 26 ##src/threads/example02.c##
  27. val = counter;## 27 ##src/threads/example02.c##
  28. printf("%d: %d\n", pthread_self(), val + 1);## 28 ##src/threads/example02.c##
  29. counter = val + 1;## 29 ##src/threads/example02.c##
  30. Pthread_mutex_unlock(&counter_mutex);## 30 ##src/threads/example02.c##
  31. }## 31 ##src/threads/example02.c##
  32. return (NULL);## 32 ##src/threads/example02.c##
  33. }## 33 ##src/threads/example02.c##