thread_annotations_unittest.nc 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2018 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. // This is a "No Compile Test" suite.
  5. // https://dev.chromium.org/developers/testing/no-compile-tests
  6. #include "base/thread_annotations.h"
  7. namespace {
  8. class LOCKABLE Lock {
  9. public:
  10. void Acquire() EXCLUSIVE_LOCK_FUNCTION() {}
  11. void Release() UNLOCK_FUNCTION() {}
  12. };
  13. class SCOPED_LOCKABLE AutoLock {
  14. public:
  15. AutoLock(Lock& lock) EXCLUSIVE_LOCK_FUNCTION(lock) : lock_(lock) {
  16. lock.Acquire();
  17. }
  18. ~AutoLock() UNLOCK_FUNCTION() { lock_.Release(); }
  19. private:
  20. Lock& lock_;
  21. };
  22. class ThreadSafe {
  23. public:
  24. void BuggyIncrement();
  25. private:
  26. Lock lock_;
  27. int counter_ GUARDED_BY(lock_);
  28. };
  29. #if defined(NCTEST_LOCK_WITHOUT_UNLOCK) // [r"fatal error: mutex 'lock_' is still held at the end of function"]
  30. void ThreadSafe::BuggyIncrement() {
  31. lock_.Acquire();
  32. ++counter_;
  33. // Forgot to release the lock.
  34. }
  35. #elif defined(NCTEST_ACCESS_WITHOUT_LOCK) // [r"fatal error: writing variable 'counter_' requires holding mutex 'lock_' exclusively"]
  36. void ThreadSafe::BuggyIncrement() {
  37. // Member access without holding the lock guarding it.
  38. ++counter_;
  39. }
  40. #elif defined(NCTEST_ACCESS_WITHOUT_SCOPED_LOCK) // [r"fatal error: writing variable 'counter_' requires holding mutex 'lock_' exclusively"]
  41. void ThreadSafe::BuggyIncrement() {
  42. {
  43. AutoLock auto_lock(lock_);
  44. // The AutoLock will go out of scope before the guarded member access.
  45. }
  46. ++counter_;
  47. }
  48. #elif defined(NCTEST_GUARDED_BY_WRONG_TYPE) // [r"fatal error: 'guarded_by' attribute requires arguments whose type is annotated"]
  49. int not_lockable;
  50. int global_counter GUARDED_BY(not_lockable);
  51. // Defined to avoid link error.
  52. void ThreadSafe::BuggyIncrement() { }
  53. #endif
  54. } // anonymous namespace