1 /* 2 * Copyright (C) 2016 The Android Open Source Project 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 CHRE_UTIL_SYNCHRONIZED_MEMORY_POOL_H_ 18 #define CHRE_UTIL_SYNCHRONIZED_MEMORY_POOL_H_ 19 20 #include "chre/platform/mutex.h" 21 #include "chre/util/memory_pool.h" 22 23 namespace chre { 24 25 /** 26 * This is a thread-safe version of the MemoryPool. 27 */ 28 template <typename ElementType, size_t kSize> 29 class SynchronizedMemoryPool : public NonCopyable { 30 public: 31 /** 32 * Allocates space for an object, constructs it and returns the pointer to 33 * that object. This method is thread-safe and a lock will be acquired 34 * upon entry to this method. 35 * 36 * @param The arguments to be forwarded to the constructor of the object. 37 * @return A pointer to a constructed object or nullptr if the allocation 38 * fails. 39 */ 40 template <typename... Args> 41 ElementType *allocate(Args &&... args); 42 43 /** 44 * Releases the memory of a previously allocated element. The pointer provided 45 * here must be one that was produced by a previous call to the allocate() 46 * function. The destructor is invoked on the object. This method is 47 * thread-safe and a lock will be acquired upon entry to this method. 48 * 49 * @param A pointer to an element that was previously allocated by the 50 * allocate() function. 51 */ 52 void deallocate(ElementType *element); 53 54 /** 55 * @return the number of unused blocks in this memory pool. 56 */ 57 size_t getFreeBlockCount(); 58 59 private: 60 //! The mutex used to guard access to this memory pool. 61 Mutex mMutex; 62 63 //! The non-synchronized MemoryPool that is used to implement this thread-safe 64 //! version. 65 MemoryPool<ElementType, kSize> mMemoryPool; 66 }; 67 68 } // namespace chre 69 70 #include "chre/util/synchronized_memory_pool_impl.h" 71 72 #endif // CHRE_UTIL_SYNCHRONIZED_MEMORY_POOL_H_ 73