Add a Reader-Writer Lock

(This is a merge of http://go/wvgerrit/70666)

We need a reader-writer lock implementation in order to make use of the
new threading guarantees in OEMCrypto v15. However, we do not have
access to an STL reader-writer lock due to only being on C++11. This
patch adds a home-grown reader-writer lock, as well as tests to verify
that its behavior is sound.

Bug: 70889998
Bug: 118584039
Test: CE CDM Unit Tests
Test: Android Unit Tests
Change-Id: Iaddcefb50e72452fbd27d04879eacf775484e675
This commit is contained in:
John W. Bruce
2019-01-29 13:41:38 -08:00
parent 19c4996b3c
commit a1b5b42d55
7 changed files with 425 additions and 0 deletions

View File

@@ -0,0 +1,60 @@
// Copyright 2019 Google LLC. All Rights Reserved. This file and proprietary
// source code may only be used and distributed under the Widevine Master
// License Agreement.
#include "rw_lock.h"
#include "log.h"
namespace wvcdm {
shared_mutex::~shared_mutex() {
if (reader_count_ > 0) {
LOGE("shared_mutex destroyed with active readers!");
}
if (has_writer_) {
LOGE("shared_mutex destroyed with an active writer!");
}
}
void shared_mutex::lock_shared() {
std::unique_lock<std::mutex> lock(mutex_);
while (has_writer_) {
condition_variable_.wait(lock);
}
++reader_count_;
}
void shared_mutex::unlock_shared() {
std::unique_lock<std::mutex> lock(mutex_);
--reader_count_;
if (reader_count_ == 0) {
condition_variable_.notify_all();
}
}
bool shared_mutex::lock_implementation(bool abort_if_unavailable) {
std::unique_lock<std::mutex> lock(mutex_);
while (reader_count_ > 0 || has_writer_) {
if (abort_if_unavailable) return false;
condition_variable_.wait(lock);
}
has_writer_ = true;
return true;
}
void shared_mutex::unlock() {
std::unique_lock<std::mutex> lock(mutex_);
has_writer_ = false;
condition_variable_.notify_all();
}
} // namespace wvcdm