A simple read/write spin lock

 

class RWSpinLock {
  public:
    RWSpinLock();
    void readLock();
    void readUnlock();
    void writeLock();
    void writeUnlock();

  private:
    const static uint32_t WRITING = 0x80000000u;
    volatile uint32_t state;

    RWSpinLock(const RWSpinLock&);
    RWSpinLock& operator= (const RWSpinLock&);
};

RWSpinLock::RWSpinLock() : state(0) {}

void RWSpinLock::readLock() {
  while(atomic_inc_32_nv(&state) > WRITING)
    atomic_dec_32(&state);
}

void RWSpinLock::readUnlock() {
  atomic_dec_32(&state);
}

void RWSpinLock::writeLock() {
  while(atomic_cas_32(&state, 0, WRITING));
}

void RWSpinLock::writeUnlock() {
  atomic_add_32(&state, -static_cast<int32_t>(WRITING));
}

Advertisements
This entry was posted in Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s