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