5 * Use, modification and distribution are subject to the
6 * Boost Software License, Version 1.0. (See accompanying file
7 * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
12 * LOCATION: see http://www.boost.org for most recent version.
13 * FILE mem_block_cache.hpp
14 * VERSION see <boost/version.hpp>
15 * DESCRIPTION: memory block cache used by the non-recursive matcher.
18 #ifndef BOOST_REGEX_V4_MEM_BLOCK_CACHE_HPP
19 #define BOOST_REGEX_V4_MEM_BLOCK_CACHE_HPP
22 #ifdef BOOST_HAS_THREADS
23 #include <boost/regex/pending/static_mutex.hpp>
26 #ifdef BOOST_HAS_ABI_HEADERS
27 # include BOOST_ABI_PREFIX
30 #ifndef BOOST_NO_CXX11_HDR_ATOMIC
32 #if ATOMIC_POINTER_LOCK_FREE == 2
33 #define BOOST_REGEX_MEM_BLOCK_CACHE_LOCK_FREE
34 #define BOOST_REGEX_ATOMIC_POINTER std::atomic
39 namespace BOOST_REGEX_DETAIL_NS{
41 #ifdef BOOST_REGEX_MEM_BLOCK_CACHE_LOCK_FREE /* lock free implementation */
42 struct mem_block_cache
44 std::atomic<void*> cache[BOOST_REGEX_MAX_CACHE_BLOCKS];
48 for (size_t i = 0;i < BOOST_REGEX_MAX_CACHE_BLOCKS; ++i) {
49 if (cache[i].load()) ::operator delete(cache[i].load());
54 for (size_t i = 0;i < BOOST_REGEX_MAX_CACHE_BLOCKS; ++i) {
55 void* p = cache[i].load();
57 if (cache[i].compare_exchange_strong(p, NULL)) return p;
60 return ::operator new(BOOST_REGEX_BLOCKSIZE);
64 for (size_t i = 0;i < BOOST_REGEX_MAX_CACHE_BLOCKS; ++i) {
65 void* p = cache[i].load();
67 if (cache[i].compare_exchange_strong(p, ptr)) return;
70 ::operator delete(ptr);
73 static mem_block_cache& instance()
75 static mem_block_cache block_cache = { { {nullptr} } };
81 #else /* lock-based implementation */
89 struct mem_block_cache
91 // this member has to be statically initialsed:
93 unsigned cached_blocks;
94 #ifdef BOOST_HAS_THREADS
95 boost::static_mutex mut;
102 mem_block_node* old = next;
104 ::operator delete(old);
109 #ifdef BOOST_HAS_THREADS
110 boost::static_mutex::scoped_lock g(mut);
114 mem_block_node* result = next;
119 return ::operator new(BOOST_REGEX_BLOCKSIZE);
123 #ifdef BOOST_HAS_THREADS
124 boost::static_mutex::scoped_lock g(mut);
126 if(cached_blocks >= BOOST_REGEX_MAX_CACHE_BLOCKS)
128 ::operator delete(p);
132 mem_block_node* old = static_cast<mem_block_node*>(p);
138 static mem_block_cache& instance()
140 #ifdef BOOST_HAS_THREADS
141 static mem_block_cache block_cache = { 0, 0, BOOST_STATIC_MUTEX_INIT, };
143 static mem_block_cache block_cache = { 0, 0, };
150 #if BOOST_REGEX_MAX_CACHE_BLOCKS == 0
152 inline void* BOOST_REGEX_CALL get_mem_block()
154 return ::operator new(BOOST_REGEX_BLOCKSIZE);
157 inline void BOOST_REGEX_CALL put_mem_block(void* p)
159 ::operator delete(p);
164 inline void* BOOST_REGEX_CALL get_mem_block()
166 return mem_block_cache::instance().get();
169 inline void BOOST_REGEX_CALL put_mem_block(void* p)
171 mem_block_cache::instance().put(p);
178 #ifdef BOOST_HAS_ABI_HEADERS
179 # include BOOST_ABI_SUFFIX