Skip to content

Commit 8f35536

Browse files
committed
added readwritelock implementation
1 parent b42f418 commit 8f35536

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed
+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
//
2+
// Created by plamen5kov on 9/10/16.
3+
//
4+
5+
#include "ReadWriteLock.h"
6+
7+
using namespace std;
8+
using namespace tns;
9+
10+
ReadWriteLock::ReadWriteLock()
11+
: shared(), reader_gate(), writer_gate(), active_readers(0), waiting_writers(0), active_writers(0)
12+
{
13+
}
14+
15+
void ReadWriteLock::AquireReadLock() {
16+
//wait till there are no waiting writers and increment active readers
17+
std::unique_lock<std::mutex> lk(shared);
18+
while( waiting_writers != 0 ) //starving readers and giving writer priority
19+
{
20+
reader_gate.wait(lk);
21+
}
22+
active_readers++;
23+
lk.unlock();
24+
}
25+
26+
void ReadWriteLock::ReleaseReadUnlock() {
27+
//get lock decrement active readers and notify one waiting writer
28+
std::unique_lock<std::mutex> lk(shared);
29+
active_readers--;
30+
lk.unlock();
31+
writer_gate.notify_one();
32+
}
33+
34+
void ReadWriteLock::AquireWriteLock() {
35+
//declare waiting and wait till there are no more active readers or writers and get lock
36+
std::unique_lock<std::mutex> lk(shared);
37+
waiting_writers++;
38+
while( active_readers != 0 || active_writers != 0 ) //if any is active wait for them to finish
39+
{
40+
writer_gate.wait(lk);
41+
}
42+
active_writers++;
43+
lk.unlock();
44+
}
45+
46+
void ReadWriteLock::ReleaseWriteUnlock() {
47+
//decrement waiting and active writers
48+
std::unique_lock<std::mutex> lk(shared);
49+
waiting_writers--;
50+
active_writers--;
51+
if(waiting_writers > 0)
52+
writer_gate.notify_one(); //(priority to writers)
53+
else
54+
reader_gate.notify_all(); //notify readers
55+
lk.unlock();
56+
}
57+

runtime/src/main/jni/ReadWriteLock.h

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
//
2+
// Created by plamen5kov on 9/10/16.
3+
//
4+
5+
#ifndef READWRITELOCK_H
6+
#define READWRITELOCK_H
7+
8+
#include <iostream>
9+
#include <mutex>
10+
#include <condition_variable>
11+
12+
namespace tns {
13+
14+
class ReadWriteLock
15+
{
16+
public:
17+
ReadWriteLock();
18+
19+
void AquireReadLock();
20+
void ReleaseReadUnlock();
21+
void AquireWriteLock();
22+
void ReleaseWriteUnlock();
23+
24+
private:
25+
std::mutex shared;
26+
std::condition_variable reader_gate;
27+
std::condition_variable writer_gate;
28+
int active_readers;
29+
int active_writers;
30+
int waiting_writers;
31+
};
32+
}
33+
34+
#endif //READWRITELOCK_H

0 commit comments

Comments
 (0)