atomic_xchg.c 887 B

1234567891011121314151617181920212223242526272829303132333435
  1. /*
  2. * Copyright (C) 2023 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "peterson.h"
  6. void
  7. peterson_lock_acquire(peterson_lock_t *lock, int thread_id)
  8. {
  9. bool xchg_ret1;
  10. int xchg_ret2;
  11. // this threads wants to enter the cs
  12. __atomic_exchange(&lock->flag[thread_id], &(bool){ true }, &xchg_ret1,
  13. __ATOMIC_SEQ_CST);
  14. // assume the other thread has priority
  15. int other_thread = 1 - thread_id;
  16. __atomic_exchange(&lock->turn, &other_thread, &xchg_ret2, __ATOMIC_SEQ_CST);
  17. while (lock->turn == other_thread && lock->flag[other_thread]) {
  18. // Busy wait
  19. }
  20. }
  21. int
  22. main()
  23. {
  24. pthread_t thread1, thread2;
  25. printf("============ test peterson lock using atomic xchg ============\n");
  26. run_test(&thread1, &thread2, test_peterson_lock_atomicity);
  27. return 0;
  28. }