2 * Copyright 2014 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.
17 #ifndef FOLLY_THREADCACHEDARENA_H_
18 #define FOLLY_THREADCACHEDARENA_H_
23 #include <boost/intrusive/slist.hpp>
25 #include <folly/Likely.h>
26 #include <folly/Arena.h>
27 #include <folly/ThreadLocal.h>
32 * Thread-caching arena: allocate memory which gets freed when the arena gets
35 * The arena itself allocates memory using malloc() in blocks of
36 * at least minBlockSize bytes.
38 * For speed, each thread gets its own Arena (see Arena.h); when threads
39 * exit, the Arena gets merged into a "zombie" Arena, which will be deallocated
40 * when the ThreadCachedArena object is destroyed.
42 class ThreadCachedArena {
44 explicit ThreadCachedArena(
45 size_t minBlockSize = SysArena::kDefaultMinBlockSize,
46 size_t maxAlign = SysArena::kDefaultMaxAlign);
48 void* allocate(size_t size) {
49 SysArena* arena = arena_.get();
50 if (UNLIKELY(!arena)) {
51 arena = allocateThreadLocalArena();
54 return arena->allocate(size);
57 void deallocate(void* p) {
62 ThreadCachedArena(const ThreadCachedArena&) = delete;
63 ThreadCachedArena(ThreadCachedArena&&) = delete;
64 ThreadCachedArena& operator=(const ThreadCachedArena&) = delete;
65 ThreadCachedArena& operator=(ThreadCachedArena&&) = delete;
67 SysArena* allocateThreadLocalArena();
69 // Zombify the blocks in arena, saving them for deallocation until
70 // the ThreadCachedArena is destroyed.
71 void zombify(SysArena&& arena);
73 const size_t minBlockSize_;
74 const size_t maxAlign_;
75 SysArena zombies_; // allocated from threads that are now dead
76 std::mutex zombiesMutex_;
77 ThreadLocalPtr<SysArena> arena_; // per-thread arena
81 struct IsArenaAllocator<ThreadCachedArena> : std::true_type { };
85 #endif /* FOLLY_THREADCACHEDARENA_H_ */