atomic_store.c 797 B

1234567891011121314151617181920212223242526272829303132
  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. // this threads wants to enter the cs
  10. __atomic_store(&lock->flag[thread_id], &(bool){ true }, __ATOMIC_SEQ_CST);
  11. // assume the other thread has priority
  12. int other_thread = 1 - thread_id;
  13. __atomic_store(&lock->turn, &other_thread, __ATOMIC_SEQ_CST);
  14. while (lock->turn == other_thread && lock->flag[other_thread]) {
  15. // Busy wait
  16. }
  17. }
  18. int
  19. main()
  20. {
  21. pthread_t thread1, thread2;
  22. printf("============ test peterson lock using atomic store ============\n");
  23. run_test(&thread1, &thread2, test_peterson_lock_atomicity);
  24. return 0;
  25. }