Path: blob/master/Utilities/cmcppdap/src/rwmutex_test.cpp
3153 views
// Copyright 2020 Google LLC1//2// Licensed under the Apache License, Version 2.0 (the "License");3// you may not use this file except in compliance with the License.4// You may obtain a copy of the License at5//6// https://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314#include "rwmutex.h"1516#include "gmock/gmock.h"17#include "gtest/gtest.h"1819#include <array>20#include <thread>21#include <vector>2223namespace {24constexpr const size_t NumThreads = 8;25}2627// Check that WLock behaves like regular mutex.28TEST(RWMutex, WLock) {29dap::RWMutex rwmutex;30int counter = 0;3132std::vector<std::thread> threads;33for (size_t i = 0; i < NumThreads; i++) {34threads.emplace_back([&] {35for (int j = 0; j < 1000; j++) {36dap::WLock lock(rwmutex);37counter++;38EXPECT_EQ(counter, 1);39counter--;40}41});42}4344for (auto& thread : threads) {45thread.join();46}4748EXPECT_EQ(counter, 0);49}5051TEST(RWMutex, NoRLockWithWLock) {52dap::RWMutex rwmutex;5354std::vector<std::thread> threads;55std::array<int, NumThreads> counters = {};5657{ // With WLock held...58dap::WLock wlock(rwmutex);5960for (size_t i = 0; i < counters.size(); i++) {61int* counter = &counters[i];62threads.emplace_back([&rwmutex, counter] {63dap::RLock lock(rwmutex);64for (int j = 0; j < 1000; j++) {65(*counter)++;66}67});68}6970// RLocks should block71for (int counter : counters) {72EXPECT_EQ(counter, 0);73}74}7576for (auto& thread : threads) {77thread.join();78}7980for (int counter : counters) {81EXPECT_EQ(counter, 1000);82}83}8485TEST(RWMutex, NoWLockWithRLock) {86dap::RWMutex rwmutex;8788std::vector<std::thread> threads;89size_t counter = 0;9091{ // With RLocks held...92dap::RLock rlockA(rwmutex);93dap::RLock rlockB(rwmutex);94dap::RLock rlockC(rwmutex);9596for (size_t i = 0; i < NumThreads; i++) {97threads.emplace_back(std::thread([&] {98dap::WLock lock(rwmutex);99counter++;100}));101}102103// ... WLocks should block104EXPECT_EQ(counter, 0U);105}106107for (auto& thread : threads) {108thread.join();109}110111EXPECT_EQ(counter, NumThreads);112}113114115