mercredi 29 juin 2016

C++11 Recursive Spinlock Implementation

Following [1] I tried to implement a recursive spin lock as follows.

class SpinLock {
public:
  SpinLock() : lock_owner(lock_is_free), lock_count(0) {
  }

  inline bool tryLock() {
    if (lock_owner != std::this_thread::get_id()) {
      bool locked = lock_owner.compare_exchange_strong(lock_is_free,
          std::this_thread::get_id(), std::memory_order_acquire,
          std::memory_order_relaxed);
      if (locked) {
        lock_count++;
      }
      return locked;
    }

    lock_count++;
    return true;
  }

  inline void lock() {
    if (lock_owner != std::this_thread::get_id()) {
      while(!lock_owner.compare_exchange_weak(lock_is_free,
            std::this_thread::get_id(), std::memory_order_acquire,
            std::memory_order_relaxed));
      assert(lock_owner == std::this_thread::get_id());
    } else {
      printf("Recursive lockingn");
    }

    lock_count++;
  }

  inline void unlock() {
    assert(lock_owner == std::this_thread::get_id());
    assert(lock_count != 0);

    --lock_count;
    if (lock_count == 0) {
      lock_owner.store(lock_is_free, std::memory_order_release);
    }
  }

  inline bool isOwner() {
    return lock_owner == std::this_thread::get_id();
  }

  inline bool isSet() {
    return lock_owner != lock_is_free;
  }

private:
  std::thread::id lock_is_free;
  std::atomic<std::thread::id> lock_owner;
  int lock_count;
};

But lock method doesn't seem to ensure mutual exclusion when I tried locking with multiple threads. What am I doing wrong here?

[1] http://codereview.stackexchange.com/questions/95590/c11-recursive-atomic-spinlock

Aucun commentaire:

Enregistrer un commentaire