Advertisement
Ilya_konstantinov

Untitled

Dec 7th, 2024
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.77 KB | Source Code | 0 0
  1. #include <linux/futex.h>
  2. #include <sys/syscall.h>
  3. #include <sys/time.h>
  4. #include <unistd.h>
  5. #include "mutex.h"
  6. #include <atomic>
  7.  
  8. void FutexWait(std::atomic<int> *value, uint64_t expected_value) {
  9.     syscall(SYS_futex, value, FUTEX_WAIT_PRIVATE, expected_value, nullptr, nullptr, 0);
  10. }
  11.  
  12. void FutexWake(std::atomic<int> *value, int count) {
  13.     syscall(SYS_futex, value, FUTEX_WAKE_PRIVATE, count, nullptr, nullptr, 0);
  14. }
  15.  
  16. void Mutex::Lock() {
  17.     int c = 0;
  18.     if (!val_.compare_exchange_strong(c, 1)) {
  19.         c = val_.exchange(2);
  20.         while (c != 0) {
  21.             FutexWait(&val_, 2);
  22.             c = val_.exchange(2);
  23.         }
  24.     }
  25. }
  26.  
  27. void Mutex::Unlock() {
  28.     if (val_.fetch_sub(1) != 1) {
  29.         val_ = 0;
  30.         FutexWake(&val_, 1);
  31.     }
  32. }
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement