|
| 1 | +/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. |
| 2 | +
|
| 3 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +you may not use this file except in compliance with the License. |
| 5 | +You may obtain a copy of the License at |
| 6 | +
|
| 7 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +
|
| 9 | +Unless required by applicable law or agreed to in writing, software |
| 10 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +See the License for the specific language governing permissions and |
| 13 | +limitations under the License. */ |
| 14 | + |
| 15 | +#include "paddle/fluid/framework/rw_lock.h" |
| 16 | +#include <gtest/gtest.h> |
| 17 | +#include <chrono> // NOLINT |
| 18 | +#include <thread> // NOLINT |
| 19 | +#include <vector> |
| 20 | + |
| 21 | +namespace f = paddle::framework; |
| 22 | + |
| 23 | +void f1(f::RWLock *lock) { |
| 24 | + lock->RDLock(); |
| 25 | + lock->UNLock(); |
| 26 | +} |
| 27 | + |
| 28 | +TEST(RWLOCK, read_read) { |
| 29 | + f::RWLock lock; |
| 30 | + lock.RDLock(); |
| 31 | + std::thread t1(f1, &lock); |
| 32 | + std::thread t2(f1, &lock); |
| 33 | + t1.join(); |
| 34 | + t2.join(); |
| 35 | + lock.UNLock(); |
| 36 | +} |
| 37 | + |
| 38 | +void f2(f::RWLock *lock, std::vector<int> *result) { |
| 39 | + lock->RDLock(); |
| 40 | + ASSERT_EQ(result->size(), 0UL); |
| 41 | + lock->UNLock(); |
| 42 | +} |
| 43 | + |
| 44 | +void f3(f::RWLock *lock, std::vector<int> *result) { |
| 45 | + lock->WRLock(); |
| 46 | + result->push_back(1); |
| 47 | + lock->UNLock(); |
| 48 | +} |
| 49 | + |
| 50 | +TEST(RWLOCK, read_write) { |
| 51 | + f::RWLock lock; |
| 52 | + std::vector<int> result; |
| 53 | + |
| 54 | + lock.RDLock(); |
| 55 | + std::thread t1(f2, &lock, &result); |
| 56 | + t1.join(); |
| 57 | + std::thread t2(f3, &lock, &result); |
| 58 | + std::this_thread::sleep_for(std::chrono::seconds(1)); |
| 59 | + ASSERT_EQ(result.size(), 0UL); |
| 60 | + lock.UNLock(); |
| 61 | + t2.join(); |
| 62 | + ASSERT_EQ(result.size(), 1UL); |
| 63 | +} |
| 64 | + |
| 65 | +void f4(f::RWLock *lock, std::vector<int> *result) { |
| 66 | + lock->RDLock(); |
| 67 | + ASSERT_EQ(result->size(), 1UL); |
| 68 | + lock->UNLock(); |
| 69 | +} |
| 70 | + |
| 71 | +TEST(RWLOCK, write_read) { |
| 72 | + f::RWLock lock; |
| 73 | + std::vector<int> result; |
| 74 | + |
| 75 | + lock.WRLock(); |
| 76 | + std::thread t1(f4, &lock, &result); |
| 77 | + std::this_thread::sleep_for(std::chrono::seconds(1)); |
| 78 | + result.push_back(1); |
| 79 | + lock.UNLock(); |
| 80 | + t1.join(); |
| 81 | +} |
0 commit comments