1 // Copyright 2018 The Chromium Authors 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 7 #include "base/memory/raw_ref.h" 8 #include "testing/gtest/include/gtest/gtest.h" 9 10 namespace { 11 12 class LOCKABLE Lock { 13 public: Acquire()14 void Acquire() EXCLUSIVE_LOCK_FUNCTION() {} Release()15 void Release() UNLOCK_FUNCTION() {} 16 }; 17 18 class SCOPED_LOCKABLE AutoLock { 19 public: EXCLUSIVE_LOCK_FUNCTION(lock)20 AutoLock(Lock& lock) EXCLUSIVE_LOCK_FUNCTION(lock) : lock_(lock) { 21 lock.Acquire(); 22 } UNLOCK_FUNCTION()23 ~AutoLock() UNLOCK_FUNCTION() { lock_->Release(); } 24 25 private: 26 const raw_ref<Lock> lock_; 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 ExplicitIncrement()39void ThreadSafe::ExplicitIncrement() { 40 lock_.Acquire(); 41 ++counter_; 42 lock_.Release(); 43 } 44 ImplicitIncrement()45void ThreadSafe::ImplicitIncrement() { 46 AutoLock auto_lock(lock_); 47 counter_++; 48 } 49 TEST(ThreadAnnotationsTest,ExplicitIncrement)50TEST(ThreadAnnotationsTest, ExplicitIncrement) { 51 ThreadSafe thread_safe; 52 thread_safe.ExplicitIncrement(); 53 } TEST(ThreadAnnotationsTest,ImplicitIncrement)54TEST(ThreadAnnotationsTest, ImplicitIncrement) { 55 ThreadSafe thread_safe; 56 thread_safe.ImplicitIncrement(); 57 } 58 59 } // anonymous namespace 60