2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <type_traits>
21 #include <folly/Arena.h>
22 #include <folly/Likely.h>
23 #include <folly/Synchronized.h>
24 #include <folly/ThreadLocal.h>
29 * Thread-caching arena: allocate memory which gets freed when the arena gets
32 * The arena itself allocates memory using malloc() in blocks of
33 * at least minBlockSize bytes.
35 * For speed, each thread gets its own Arena (see Arena.h); when threads
36 * exit, the Arena gets merged into a "zombie" Arena, which will be deallocated
37 * when the ThreadCachedArena object is destroyed.
39 class ThreadCachedArena {
41 explicit ThreadCachedArena(
42 size_t minBlockSize = SysArena::kDefaultMinBlockSize,
43 size_t maxAlign = SysArena::kDefaultMaxAlign);
45 void* allocate(size_t size) {
46 SysArena* arena = arena_.get();
47 if (UNLIKELY(!arena)) {
48 arena = allocateThreadLocalArena();
51 return arena->allocate(size);
54 void deallocate(void* /* p */) {
58 // Gets the total memory used by the arena
59 size_t totalSize() const;
62 struct ThreadLocalPtrTag {};
64 ThreadCachedArena(const ThreadCachedArena&) = delete;
65 ThreadCachedArena(ThreadCachedArena&&) = delete;
66 ThreadCachedArena& operator=(const ThreadCachedArena&) = delete;
67 ThreadCachedArena& operator=(ThreadCachedArena&&) = delete;
69 SysArena* allocateThreadLocalArena();
71 // Zombify the blocks in arena, saving them for deallocation until
72 // the ThreadCachedArena is destroyed.
73 void zombify(SysArena&& arena);
75 const size_t minBlockSize_;
76 const size_t maxAlign_;
78 ThreadLocalPtr<SysArena, ThreadLocalPtrTag> arena_; // Per-thread arena.
80 // Allocations from threads that are now dead.
81 Synchronized<SysArena> zombies_;
85 struct IsArenaAllocator<ThreadCachedArena> : std::true_type { };