peterson.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright (C) 2023 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include <stdio.h>
  6. #include <pthread.h>
  7. #include <stdbool.h>
  8. // Peterson's algorithm for mutual exclusion
  9. #define ITERATIONS 15000000
  10. typedef struct {
  11. bool flag[2];
  12. int turn;
  13. } peterson_lock_t;
  14. static int counter = 0;
  15. static peterson_lock_t lock;
  16. void
  17. peterson_lock_acquire(peterson_lock_t *lock, int thread_id);
  18. void
  19. peterson_lock_release(peterson_lock_t *lock, int thread_id)
  20. {
  21. lock->flag[thread_id] = false;
  22. }
  23. void *
  24. test_peterson_lock_atomicity(void *arg)
  25. {
  26. int thread_id = (int)(long)arg;
  27. for (int i = 0; i < ITERATIONS; ++i) {
  28. peterson_lock_acquire(&lock, thread_id);
  29. counter++;
  30. peterson_lock_release(&lock, thread_id);
  31. }
  32. return NULL;
  33. }
  34. int
  35. run_test(pthread_t *thread1_ptr, pthread_t *thread2_ptr,
  36. void *(*start_routine)(void *))
  37. {
  38. lock.flag[0] = false;
  39. lock.flag[1] = false;
  40. lock.turn = 0;
  41. counter = 0;
  42. pthread_create(thread1_ptr, NULL, start_routine, (void *)0);
  43. pthread_create(thread2_ptr, NULL, start_routine, (void *)1);
  44. pthread_join(*thread1_ptr, NULL);
  45. pthread_join(*thread2_ptr, NULL);
  46. printf("Expected counter value: %d\n", ITERATIONS * 2);
  47. printf("Actual counter value: %d\n", counter);
  48. if (counter != ITERATIONS * 2)
  49. __builtin_trap();
  50. return 0;
  51. }