sync.pthread.c 1.1 KB

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