Skip to content

Instantly share code, notes, and snippets.

@pdu
Last active May 19, 2016 02:06
Show Gist options
  • Save pdu/4338013 to your computer and use it in GitHub Desktop.
Save pdu/4338013 to your computer and use it in GitHub Desktop.
algos: use mutex to implement read-write lock
extern "C"
{
#include <pthread.h>
}
class MyRWLock
{
public:
MyRWLock();
~MyRWLock();
void r_lock();
void r_unlock();
void w_lock();
void w_unlock();
private:
int key;
pthread_mutex_t mutex_r_lock;
pthread_mutex_t mutex_w_lock;
};
MyRWLock::MyRWLock()
{
key = 0;
pthread_mutex_init(&mutex_r_lock, 0);
pthread_mutex_init(&mutex_w_lock, 0);
}
MyRWLock::~MyRWLock()
{
pthread_mutex_destroy(&mutex_r_lock);
pthread_mutex_destroy(&mutex_w_lock);
}
void MyRWLock::r_lock()
{
pthread_mutex_lock(&mutex_r_lock);
key++;
if (1 == key)
{
pthread_mutex_lock(&mutex_w_lock);
}
pthread_mutex_unlock(&mutex_r_lock);
}
void MyRWLock::r_unlock()
{
pthread_mutex_lock(&mutex_r_lock);
key--;
if (0 == key)
{
pthread_mutex_unlock(&mutex_w_lock);
}
pthread_mutex_unlock(&mutex_r_lock);
}
void MyRWLock::w_lock()
{
pthread_mutex_lock(&mutex_w_lock);
}
void MyRWLock::w_unlock()
{
pthread_mutex_unlock(&mutex_w_lock);
}
int main()
{
MyRWLock t;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment