2 * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
11 #ifndef WEBRTC_MODULES_AUDIO_CONFERENCE_MIXER_SOURCE_MEMORY_POOL_GENERIC_H_
12 #define WEBRTC_MODULES_AUDIO_CONFERENCE_MIXER_SOURCE_MEMORY_POOL_GENERIC_H_
17 #include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
18 #include "webrtc/typedefs.h"
21 template<class MemoryType>
25 // MemoryPool functions.
26 int32_t PopMemory(MemoryType*& memory);
27 int32_t PushMemory(MemoryType*& memory);
29 MemoryPoolImpl(int32_t initialPoolSize);
36 // Non-atomic function.
37 int32_t CreateMemory(uint32_t amountToCreate);
39 CriticalSectionWrapper* _crit;
43 std::list<MemoryType*> _memoryPool;
45 uint32_t _initialPoolSize;
46 uint32_t _createdMemory;
47 uint32_t _outstandingMemory;
50 template<class MemoryType>
51 MemoryPoolImpl<MemoryType>::MemoryPoolImpl(int32_t initialPoolSize)
52 : _crit(CriticalSectionWrapper::CreateCriticalSection()),
54 _initialPoolSize(initialPoolSize),
60 template<class MemoryType>
61 MemoryPoolImpl<MemoryType>::~MemoryPoolImpl()
63 // Trigger assert if there is outstanding memory.
64 assert(_createdMemory == 0);
65 assert(_outstandingMemory == 0);
69 template<class MemoryType>
70 int32_t MemoryPoolImpl<MemoryType>::PopMemory(MemoryType*& memory)
72 CriticalSectionScoped cs(_crit);
78 if (_memoryPool.empty()) {
79 // _memoryPool empty create new memory.
80 CreateMemory(_initialPoolSize);
81 if(_memoryPool.empty())
87 memory = _memoryPool.front();
88 _memoryPool.pop_front();
93 template<class MemoryType>
94 int32_t MemoryPoolImpl<MemoryType>::PushMemory(MemoryType*& memory)
100 CriticalSectionScoped cs(_crit);
101 _outstandingMemory--;
102 if(_memoryPool.size() > (_initialPoolSize << 1))
104 // Reclaim memory if less than half of the pool is unused.
110 _memoryPool.push_back(memory);
115 template<class MemoryType>
116 bool MemoryPoolImpl<MemoryType>::Initialize()
118 CriticalSectionScoped cs(_crit);
119 return CreateMemory(_initialPoolSize) == 0;
122 template<class MemoryType>
123 int32_t MemoryPoolImpl<MemoryType>::Terminate()
125 CriticalSectionScoped cs(_crit);
126 assert(_createdMemory == _outstandingMemory + _memoryPool.size());
129 // Reclaim all memory.
130 while(_createdMemory > 0)
132 MemoryType* memory = _memoryPool.front();
133 _memoryPool.pop_front();
140 template<class MemoryType>
141 int32_t MemoryPoolImpl<MemoryType>::CreateMemory(
142 uint32_t amountToCreate)
144 for(uint32_t i = 0; i < amountToCreate; i++)
146 MemoryType* memory = new MemoryType();
151 _memoryPool.push_back(memory);
156 } // namespace webrtc
158 #endif // WEBRTC_MODULES_AUDIO_CONFERENCE_MIXER_SOURCE_MEMORY_POOL_GENERIC_H_