example01.lc 1.7 KB

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