From 1c15b5bb9efd09201a956885e863fc8815c67b87 Mon Sep 17 00:00:00 2001 From: Giuseppe Ottaviano Date: Sat, 12 Mar 2016 16:12:44 -0800 Subject: [PATCH] Fix warning in MicroLock initialization Summary:The `init()` function uses the previous value of `lock_`, but that is uninitialized and the compiler can issue a warning about it. It is also potentially undefined behavior because it is not guaranteed that the address of `lock_` is taken before `init()` (in which case the it would be just an indeterminate value). Since it is not very useful to initialize only one slot and leave the others uninitialized, we can just have a single `init()` that zero-initializes all the slots. Reviewed By: dcolascione Differential Revision: D3042629 fb-gh-sync-id: de1633b02eb1c891e310f2d5d2cfc5376cd41d5f shipit-source-id: de1633b02eb1c891e310f2d5d2cfc5376cd41d5f --- folly/MicroLock.h | 4 ++-- folly/test/SmallLocksTest.cpp | 12 ++++-------- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/folly/MicroLock.h b/folly/MicroLock.h index 159e3341..8f0b09f7 100644 --- a/folly/MicroLock.h +++ b/folly/MicroLock.h @@ -102,8 +102,8 @@ class MicroLockCore { public: inline void unlock(unsigned slot); inline void unlock() { unlock(0); } - inline void init(unsigned slot) { lock_ &= ~(3U << (2 * slot)); } - inline void init() { init(0); } + // Initializes all the slots. + inline void init() { lock_ = 0; } }; inline detail::Futex<>* MicroLockCore::word() const { diff --git a/folly/test/SmallLocksTest.cpp b/folly/test/SmallLocksTest.cpp index f33e0231..7ddd29a0 100644 --- a/folly/test/SmallLocksTest.cpp +++ b/folly/test/SmallLocksTest.cpp @@ -211,7 +211,7 @@ struct SimpleBarrier { }; } -static void runMicroLockTest() { +TEST(SmallLocks, MicroLock) { volatile uint64_t counters[4] = {0, 0, 0, 0}; std::vector threads; static const unsigned nrThreads = 20; @@ -225,10 +225,7 @@ static void runMicroLockTest() { struct { uint8_t a; volatile uint8_t b; - union { - MicroLock alock; - uint8_t c; - }; + MicroLock alock; volatile uint8_t d; } x; @@ -237,7 +234,7 @@ static void runMicroLockTest() { x.a = 'a'; x.b = origB; - x.c = 0; + x.alock.init(); x.d = origD; // This thread touches other parts of the host word to show that @@ -282,17 +279,16 @@ static void runMicroLockTest() { EXPECT_EQ(x.a, 'a'); EXPECT_EQ(x.b, (uint8_t)(origB + iterPerThread / 2)); - EXPECT_EQ(x.c, 0); EXPECT_EQ(x.d, (uint8_t)(origD + iterPerThread / 2)); for (unsigned i = 0; i < 4; ++i) { EXPECT_EQ(counters[i], ((uint64_t)nrThreads * iterPerThread) / 4); } } -TEST(SmallLocks, MicroLock) { runMicroLockTest(); } TEST(SmallLocks, MicroLockTryLock) { MicroLock lock; lock.init(); EXPECT_TRUE(lock.try_lock()); EXPECT_FALSE(lock.try_lock()); + lock.unlock(); } -- 2.34.1