From 0d13183a2c02539d216e6f16f8b27a8ffb359190 Mon Sep 17 00:00:00 2001 From: Alastair Daivis Date: Sat, 2 Dec 2017 17:35:33 -0800 Subject: [PATCH] Statically allocate futex array Summary: AFAICT this is currently the only thing preventing the non-dynamic version of Folly's MPMCQueue from being allocation-free on enqueue and dequeue operations. Allocating this with a constant expression should move the allocation from runtime to link (possibly compile?) time, which will let us use it in allocation sensitive contexts. Feel free to suggest other reviewers, I couldn't find an existing folly reviewer group. Reviewed By: yfeldblum, agola11, nbronson Differential Revision: D6447848 fbshipit-source-id: 86b84b19d62f1e1bcecdb9e757a6dfa90597b084 --- folly/Portability.h | 6 ++++++ folly/detail/Futex.cpp | 16 +++++++++++----- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/folly/Portability.h b/folly/Portability.h index 6c140379..3f06c775 100644 --- a/folly/Portability.h +++ b/folly/Portability.h @@ -399,6 +399,12 @@ constexpr auto kIsObjC = true; constexpr auto kIsObjC = false; #endif +#if FOLLY_MOBILE +constexpr auto kIsMobile = true; +#else +constexpr auto kIsMobile = false; +#endif + #if defined(__linux__) && !FOLLY_MOBILE constexpr auto kIsLinux = true; #else diff --git a/folly/detail/Futex.cpp b/folly/detail/Futex.cpp index da7a04dc..a7847b18 100644 --- a/folly/detail/Futex.cpp +++ b/folly/detail/Futex.cpp @@ -16,11 +16,13 @@ #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -186,13 +188,17 @@ struct EmulatedFutexBucket { std::mutex mutex_; boost::intrusive::list waiters_; - static const size_t kNumBuckets = 4096; + static constexpr size_t const kNumBuckets = kIsMobile ? 256 : 4096; static EmulatedFutexBucket& bucketFor(void* addr) { - static auto gBuckets = new EmulatedFutexBucket[kNumBuckets]; - uint64_t mixedBits = folly::hash::twang_mix64( - reinterpret_cast(addr)); - return gBuckets[mixedBits % kNumBuckets]; + // Statically allocating this lets us use this in allocation-sensitive + // contexts. This relies on the assumption that std::mutex won't dynamically + // allocate memory, which we assume to be the case on Linux and iOS. + static Indestructible> + gBuckets; + uint64_t mixedBits = + folly::hash::twang_mix64(reinterpret_cast(addr)); + return (*gBuckets)[mixedBits % kNumBuckets]; } }; -- 2.34.1