example02.c 829 B

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