Avi Drissman | e4622aa | 2022-09-08 20:36:06 | [diff] [blame] | 1 | // Copyright 2018 The Chromium Authors |
Victor Costan | 63cd2c2d | 2018-02-16 02:29:07 | [diff] [blame] | 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "thread_annotations.h" |
| 6 | |
Ali Hijazi | a887789 | 2022-11-10 20:51:03 | [diff] [blame] | 7 | #include "base/memory/raw_ref.h" |
Victor Costan | 63cd2c2d | 2018-02-16 02:29:07 | [diff] [blame] | 8 | #include "testing/gtest/include/gtest/gtest.h" |
| 9 | |
| 10 | namespace { |
| 11 | |
| 12 | class LOCKABLE Lock { |
| 13 | public: |
| 14 | void Acquire() EXCLUSIVE_LOCK_FUNCTION() {} |
| 15 | void Release() UNLOCK_FUNCTION() {} |
| 16 | }; |
| 17 | |
| 18 | class SCOPED_LOCKABLE AutoLock { |
| 19 | public: |
Peter Kasting | 811504a7 | 2025-01-09 03:18:50 | [diff] [blame] | 20 | explicit AutoLock(Lock& lock) EXCLUSIVE_LOCK_FUNCTION(lock) : lock_(lock) { |
Victor Costan | 63cd2c2d | 2018-02-16 02:29:07 | [diff] [blame] | 21 | lock.Acquire(); |
| 22 | } |
Ali Hijazi | a887789 | 2022-11-10 20:51:03 | [diff] [blame] | 23 | ~AutoLock() UNLOCK_FUNCTION() { lock_->Release(); } |
Victor Costan | 63cd2c2d | 2018-02-16 02:29:07 | [diff] [blame] | 24 | |
| 25 | private: |
Ali Hijazi | a887789 | 2022-11-10 20:51:03 | [diff] [blame] | 26 | const raw_ref<Lock> lock_; |
Victor Costan | 63cd2c2d | 2018-02-16 02:29:07 | [diff] [blame] | 27 | }; |
| 28 | |
| 29 | class ThreadSafe { |
| 30 | public: |
| 31 | void ExplicitIncrement(); |
| 32 | void ImplicitIncrement(); |
| 33 | |
| 34 | private: |
| 35 | Lock lock_; |
| 36 | int counter_ GUARDED_BY(lock_); |
| 37 | }; |
| 38 | |
| 39 | void ThreadSafe::ExplicitIncrement() { |
| 40 | lock_.Acquire(); |
| 41 | ++counter_; |
| 42 | lock_.Release(); |
| 43 | } |
| 44 | |
| 45 | void ThreadSafe::ImplicitIncrement() { |
| 46 | AutoLock auto_lock(lock_); |
| 47 | counter_++; |
| 48 | } |
| 49 | |
| 50 | TEST(ThreadAnnotationsTest, ExplicitIncrement) { |
| 51 | ThreadSafe thread_safe; |
| 52 | thread_safe.ExplicitIncrement(); |
| 53 | } |
| 54 | TEST(ThreadAnnotationsTest, ImplicitIncrement) { |
| 55 | ThreadSafe thread_safe; |
| 56 | thread_safe.ImplicitIncrement(); |
| 57 | } |
| 58 | |
| 59 | } // anonymous namespace |