2 * Copyright 2013 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);
47 void* allocate(size_t size) {
48 SysArena* arena = arena_.get();
49 if (UNLIKELY(!arena)) {
50 arena = allocateThreadLocalArena();
53 return arena->allocate(size);
56 void deallocate(void* p) {
61 ThreadCachedArena(const ThreadCachedArena&) = delete;
62 ThreadCachedArena(ThreadCachedArena&&) = delete;
63 ThreadCachedArena& operator=(const ThreadCachedArena&) = delete;
64 ThreadCachedArena& operator=(ThreadCachedArena&&) = delete;
66 SysArena* allocateThreadLocalArena();
68 // Zombify the blocks in arena, saving them for deallocation until
69 // the ThreadCachedArena is destroyed.
70 void zombify(SysArena&& arena);
73 SysArena zombies_; // allocated from threads that are now dead
74 std::mutex zombiesMutex_;
75 ThreadLocalPtr<SysArena> arena_; // per-thread arena
80 #endif /* FOLLY_THREADCACHEDARENA_H_ */