sync.pthread.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /* -*- mode:c; c-file-style:"k&r"; c-basic-offset: 4; tab-width:4; indent-tabs-mode:nil; mode:auto-fill; fill-column:78; -*- */
  2. /* vim: set ts=4 sw=4 et tw=78 fo=cqt wm=0: */
  3. #include <pthread.h>
  4. #include <stdio.h>
  5. #include <math.h>
  6. #define ITERATIONS 100000
  7. // A shared mutex
  8. pthread_mutex_t mutex;
  9. double target;
  10. void* opponent(void *arg)
  11. {
  12. int i ;
  13. for(i = 0; i < ITERATIONS; ++i)
  14. {
  15. // Lock the mutex
  16. pthread_mutex_lock(&mutex);
  17. target -= i ;
  18. // Unlock the mutex
  19. pthread_mutex_unlock(&mutex);
  20. }
  21. return NULL;
  22. }
  23. int main(int argc, char **argv)
  24. {
  25. pthread_t other;
  26. int rv;
  27. target = 5.0;
  28. // Initialize the mutex
  29. if(pthread_mutex_init(&mutex, NULL))
  30. {
  31. printf("Unable to initialize a mutex\n");
  32. return -1;
  33. }
  34. if(pthread_create(&other, NULL, &opponent, NULL))
  35. {
  36. printf("Unable to spawn thread\n");
  37. return -1;
  38. }
  39. int i;
  40. for(i = 0; i < ITERATIONS; ++i)
  41. {
  42. pthread_mutex_lock(&mutex);
  43. target += i ;
  44. pthread_mutex_unlock(&mutex);
  45. }
  46. if((rv = pthread_join(other, NULL)) < 0)
  47. {
  48. printf("Could not join thread - %d\n", rv);
  49. return -1;
  50. }
  51. // Clean up the mutex
  52. pthread_mutex_destroy(&mutex);
  53. printf("Result: %f\n", target);
  54. return 0;
  55. }