sync.pthread.c 1.1 KB

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