folly: build with -Wunused-parameter
[folly.git] / folly / ThreadCachedArena.h
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #ifndef FOLLY_THREADCACHEDARENA_H_
18 #define FOLLY_THREADCACHEDARENA_H_
19
20 #include <type_traits>
21
22 #include <folly/Arena.h>
23 #include <folly/Likely.h>
24 #include <folly/Synchronized.h>
25 #include <folly/ThreadLocal.h>
26
27 namespace folly {
28
29 /**
30  * Thread-caching arena: allocate memory which gets freed when the arena gets
31  * destroyed.
32  *
33  * The arena itself allocates memory using malloc() in blocks of
34  * at least minBlockSize bytes.
35  *
36  * For speed, each thread gets its own Arena (see Arena.h); when threads
37  * exit, the Arena gets merged into a "zombie" Arena, which will be deallocated
38  * when the ThreadCachedArena object is destroyed.
39  */
40 class ThreadCachedArena {
41  public:
42   explicit ThreadCachedArena(
43       size_t minBlockSize = SysArena::kDefaultMinBlockSize,
44       size_t maxAlign = SysArena::kDefaultMaxAlign);
45
46   void* allocate(size_t size) {
47     SysArena* arena = arena_.get();
48     if (UNLIKELY(!arena)) {
49       arena = allocateThreadLocalArena();
50     }
51
52     return arena->allocate(size);
53   }
54
55   void deallocate(void* /* p */) {
56     // Deallocate? Never!
57   }
58
59   // Gets the total memory used by the arena
60   size_t totalSize() const;
61
62  private:
63   struct ThreadLocalPtrTag {};
64
65   ThreadCachedArena(const ThreadCachedArena&) = delete;
66   ThreadCachedArena(ThreadCachedArena&&) = delete;
67   ThreadCachedArena& operator=(const ThreadCachedArena&) = delete;
68   ThreadCachedArena& operator=(ThreadCachedArena&&) = delete;
69
70   SysArena* allocateThreadLocalArena();
71
72   // Zombify the blocks in arena, saving them for deallocation until
73   // the ThreadCachedArena is destroyed.
74   void zombify(SysArena&& arena);
75
76   const size_t minBlockSize_;
77   const size_t maxAlign_;
78
79   ThreadLocalPtr<SysArena, ThreadLocalPtrTag> arena_;  // Per-thread arena.
80
81   // Allocations from threads that are now dead.
82   Synchronized<SysArena> zombies_;
83 };
84
85 template <>
86 struct IsArenaAllocator<ThreadCachedArena> : std::true_type { };
87
88 }  // namespace folly
89
90 #endif /* FOLLY_THREADCACHEDARENA_H_ */