hpp-corbaserver: include/hpp/corbaserver/read-write-lock.hh Source File

hpp-corbaserver 9.0.2 Corba server for Humanoid Path Planner applications

Loading...
Searching...
No Matches
read-write-lock.hh
Go to the documentation of this file.
1// Copyright (C) 2023 by Joseph Mirabel
2//
3// This code was taken from https://stackoverflow.com/a/28121513
4
5#include <condition_variable>
6#include <mutex>
7
8 namespace hpp {
9 namespace corbaServer {
10
17 class ReadWriteLock {
18 public:
19 ReadWriteLock()
20 : shared_(),
21 readerQ_(),
22 writerQ_(),
23 activeReaders_(0),
24 waitingWriters_(0),
25 activeWriters_(0) {}
26
27 void readLock() {
28 std::unique_lock<std::mutex> lk(shared_);
29 while (waitingWriters_ != 0) readerQ_.wait(lk);
30 ++activeReaders_;
31 lk.unlock();
32 }
33
34 void readUnlock() {
35 std::unique_lock<std::mutex> lk(shared_);
36 --activeReaders_;
37 lk.unlock();
38 writerQ_.notify_one();
39 }
40
41 void writeLock() {
42 std::unique_lock<std::mutex> lk(shared_);
43 ++waitingWriters_;
44 while (activeReaders_ != 0 || activeWriters_ != 0) writerQ_.wait(lk);
45 ++activeWriters_;
46 lk.unlock();
47 }
48
49 void writeUnlock() {
50 std::unique_lock<std::mutex> lk(shared_);
51 --waitingWriters_;
52 --activeWriters_;
53 if (waitingWriters_ > 0)
54 writerQ_.notify_one();
55 else
56 readerQ_.notify_all();
57 lk.unlock();
58 }
59
60 private:
61 std::mutex shared_;
62 std::condition_variable readerQ_;
63 std::condition_variable writerQ_;
64 int activeReaders_;
65 int waitingWriters_;
66 int activeWriters_;
67};
68
69} // end of namespace corbaServer.
70} // end of namespace hpp.
hpp::corbaServer::ReadWriteLock
Definition read-write-lock.hh:17
hpp::corbaServer::ReadWriteLock::ReadWriteLock
ReadWriteLock()
Definition read-write-lock.hh:19
hpp::corbaServer::ReadWriteLock::writeUnlock
void writeUnlock()
Definition read-write-lock.hh:49
hpp::corbaServer::ReadWriteLock::readUnlock
void readUnlock()
Definition read-write-lock.hh:34
hpp::corbaServer::ReadWriteLock::readLock
void readLock()
Definition read-write-lock.hh:27
hpp::corbaServer::ReadWriteLock::writeLock
void writeLock()
Definition read-write-lock.hh:41
hpp::corbaServer::makeServantDownCast
ReturnType::Object_var makeServantDownCast(Server *server, const typename ServantBaseType::Storage &t)
Definition servant-base.hh:407
hpp
Implement CORBA interface `‘Obstacle’'.