File: pool.h

package info (click to toggle)
bowtie 1.2.3+dfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 16,888 kB
  • sloc: cpp: 35,784; perl: 5,903; ansic: 1,247; sh: 1,180; python: 487; makefile: 426
file content (401 lines) | stat: -rw-r--r-- 8,647 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/*
 * pool.h
 */

#ifndef POOL_H_
#define POOL_H_

#include <iostream>
#include <vector>
#include <stdexcept>
#include <string.h>
#include <stdlib.h>
#include "bitset.h"
#include "log.h"
#include "search_globals.h"

/**
 * Very simple allocator for fixed-size chunks of memory.  Chunk size
 * is set at construction time.  Heap memory is only allocated at
 * construction and deallocated at destruction.
 */
class bowtieChunkPool {
public:
	/**
	 * Initialize a new pool with an initial size of about 'bytes'
	 * bytes.  Exit with an error message if we can't allocate it.
	 */
	bowtieChunkPool(uint32_t chunkSz, uint32_t totSz, bool verbose_) :
		verbose(verbose_), patid(0), pool_(NULL), cur_(0),
		chunkSz_(chunkSz), totSz_(totSz), lim_(totSz/chunkSz),
		bits_(lim_), exhaustCrash_(false),
		lastSkippedRead_(0xffffffff), readName_(NULL)
	{
		assert_gt(lim_, 0);
		try {
			if((pool_ = new int8_t[totSz_]) == NULL) {
				throw std::bad_alloc();
			}
		} catch(std::bad_alloc& e) {
			ThreadSafe _ts(&gLock);
			std::cerr << "Error: Could not allocate bowtieChunkPool of "
			          << totSz << " bytes" << std::endl;
			exhausted();
			throw 1; // Exit if we haven't already
		}
	}

	/**
	 * Delete all the pools.
	 */
	~bowtieChunkPool() {
		if(pool_ != NULL) delete[] pool_;
	}

	/**
	 * Reset the pool, freeing all arrays that had been given out.
	 */
	void reset(String<char>* name, uint32_t patid_) {
		patid = patid_;
		readName_ = name;
		cur_ = 0;
		bits_.clear();
		assert_eq(0, bits_.test(0));
	}

	/**
	 * Return our current position.
	 */
	uint32_t pos() {
		return cur_;
	}

	/**
	 * Return our current position.
	 */
	uint32_t remaining() {
		assert_geq(lim_, cur_);
		return lim_ - cur_;
	}

	/**
	 * Allocate a single T from the pool.
	 */
	void* alloc() {
		assert_lt(cur_, lim_);
		uint32_t cur = cur_;
		while(bits_.test(cur)) {
			cur++;
			if(cur >= lim_) {
				cur = 0;
			}
			if(cur == cur_) {
				// Wrapped all the way around without finding a free
				// chunk
				return NULL;
			}
		}
		void * ptr = (void *)(&pool_[cur * chunkSz_]);
		assert(!bits_.test(cur));
		bits_.set(cur);
		assert(bits_.test(cur));
		if(verbose) {
			stringstream ss;
			ss << patid << ": Allocating chunk with offset: " << cur;
			glog.msg(ss.str());
		}
		cur_ = cur;
		return ptr;
	}

	/**
	 *
	 */
	void free(void *ptr) {
		uint32_t off = (uint32_t)((int8_t*)ptr - pool_);
		assert_eq(0, off % chunkSz_);
		off /= chunkSz_;
		if(verbose) {
			stringstream ss;
			ss << patid << ": Freeing chunk with offset: " << cur_;
			glog.msg(ss.str());
		}
		bits_.clear(off);
	}

	/**
	 *
	 */
	uint32_t chunkSize() const {
		return chunkSz_;
	}

	/**
	 *
	 */
	uint32_t totalSize() const {
		return totSz_;
	}

	/**
	 * Utility function to call when memory has been exhausted.
	 * Currently just prints a friendly message and quits.
	 */
	void exhausted() {
		if(patid != lastSkippedRead_) {
			if(!exhaustCrash_ && !quiet) std::cerr << "Warning: ";
			if(!quiet) {
				std::cerr << "Exhausted best-first chunk memory for read "
				          << (*readName_) << " (patid " << patid
				          << "); skipping read" << std::endl;
			}
			if(exhaustCrash_) {
				if(!quiet) {
					std::cerr << "Please try specifying a larger --chunkmbs <int> (default is 32)" << std::endl;
				}
				throw 1;
			}
		}
		lastSkippedRead_ = patid;
	}

	bool verbose;
	uint32_t patid;

protected:

	int8_t*  pool_; /// the memory pools
	uint32_t cur_;  /// index of next free element of pool_
	const uint32_t chunkSz_;
	const uint32_t totSz_;
	uint32_t lim_;  /// # elements held in pool_
	FixedBitset2 bits_;
	bool exhaustCrash_; /// abort hard when memory's exhausted?
	uint32_t lastSkippedRead_;
	String<char>* readName_;
};

/**
 * Class for managing a pool of memory from which items of type T
 * (which must have a default constructor) are allocated.  Does not
 * support freeing or resizing individual items - just allocation and
 * then freeing all items at once.
 */
template<typename T>
class AllocOnlyPool {
	typedef std::pair<uint32_t, uint32_t> U32Pair;
public:
	/**
	 * Initialize a new pool with an initial size of about 'bytes'
	 * bytes.  Exit with an error message if we can't allocate it.
	 */
	AllocOnlyPool(bowtieChunkPool* pool, const char *name) :
		pool_(pool), name_(name), curPool_(0), cur_(0)
	{
		assert(pool != NULL);
		lim_ = pool->chunkSize() / sizeof(T);
		assert_gt(lim_, 0);
		assert_gt(lim_, 1024);
	}

	/**
	 * Reset the pool, freeing all arrays that had been given out.
	 */
	void reset() {
		pools_.clear();
		lastCurInPool_.clear();
		cur_ = 0;
		curPool_ = 0;
	}

	/**
	 * Allocate a single T from the pool.
	 */
	T* alloc() {
		if(!lazyInit()) return NULL;
		if(cur_ + 1 >= lim_) {
			if(!allocNextPool()) return NULL;
		}
		cur_ ++;
		return &pools_[curPool_][cur_ - 1];
	}

	/**
	 * Allocate a single T from the pool and clear it.
	 */
	T* allocC() {
		T* t = alloc();
		if(t != NULL) {
			memset(t, 0, sizeof(T));
		}
		return t;
	}

	/**
	 * Allocate an array of Ts from the pool.
	 */
	T* alloc(uint32_t num) {
		if(!lazyInit()) return NULL;
		if(cur_ + num >= lim_) {
			if(!allocNextPool()) return NULL;
			assert_eq(0, cur_);
		}
		assert_leq(num, lim_);
		cur_ += num;
		return &pools_[curPool_][cur_ - num];
	}

	/**
	 * Allocate an array of Ts and clear them.
	 */
	T* allocC(uint32_t num) {
		T* t = alloc(num);
		if(t != NULL) {
			memset(t, 0, sizeof(T) * num);
		}
		return t;
	}

	/**
	 * Return the current pool.
	 */
	uint32_t curPool() const {
		return curPool_;
	}

	/**
	 * Return the current position within the current pool.
	 */
	uint32_t cur() const {
		return cur_;
	}

	/**
	 * Free a pointer allocated from this pool.  Fow, we only know how
	 * to free the topmost element.
	 */
	void free(T* t) {
		assert(t != NULL);
		if(pool_->verbose) {
			stringstream ss;
			ss << pool_->patid << ": Freeing a " << name_;
			glog.msg(ss.str());
		}
		if(cur_ > 0 && t == &pools_[curPool_][cur_-1]) {
			cur_--;
			ASSERT_ONLY(memset(&pools_[curPool_][cur_], 0, sizeof(T)));
			if(cur_ == 0 && curPool_ > 0) {
				rewindPool();
			}
		}
	}

	/**
	 * Free an array of pointers allocated from this pool.  For now, we
	 * only know how to free the topmost array.
	 */
	bool free(T* t, uint32_t num) {
		assert(t != NULL);
		if(pool_->verbose) {
			stringstream ss;
			ss << pool_->patid << ": Freeing " << num << " " << name_ << "s";
			glog.msg(ss.str());
		}
		if(num <= cur_ && t == &pools_[curPool_][cur_ - num]) {
			cur_ -= num;
			ASSERT_ONLY(memset(&pools_[curPool_][cur_], 0, num * sizeof(T)));
			if(cur_ == 0 && curPool_ > 0) {
				rewindPool();
			}
			return true; // deallocated
		}
		return false; // didn't deallocate
	}

	/**
	 * Return a unique (with respect to every other object allocated
	 * from this pool) identifier for the last object that was just
	 * allocated.
	 */
	uint32_t lastId() const {
		return (curPool_ << 16) | cur_;
	}

#ifndef NDEBUG
	bool empty() const {
		assert(pools_.empty());
		assert_eq(0, cur_);
		assert_eq(0, curPool_);
		return true;
	}
#endif

protected:

	bool allocNextPool() {
		assert_eq(curPool_+1, pools_.size());
		T *pool;
		try {
			if((pool = (T*)pool_->alloc()) == NULL) {
				throw std::bad_alloc();
			}
		} catch(std::bad_alloc& e) {
			ThreadSafe _ts(&gLock);
			pool_->exhausted();
			return false;
		}
		ASSERT_ONLY(memset(pool, 0, lim_ * sizeof(T)));
		pools_.push_back(pool);
		lastCurInPool_.push_back(cur_);
		curPool_++;
		cur_ = 0;
		return true;
	}

	bool lazyInit() {
		if(cur_ == 0 && pools_.empty()) {
			T *pool;
			try {
				if((pool = (T*)pool_->alloc()) == NULL) {
					throw std::bad_alloc();
				}
			} catch(std::bad_alloc& e) {
				ThreadSafe _ts(&gLock);
				pool_->exhausted();
				return false;
			}
			ASSERT_ONLY(memset(pool, 0, lim_ * sizeof(T)));
			pools_.push_back(pool);
			assert_eq(1, pools_.size());
		}
		assert(!pools_.empty());
		return true;
	}

	void rewindPool() {
		assert_eq(curPool_+1, pools_.size());
		assert_eq(curPool_, lastCurInPool_.size());
		if(pool_->verbose) {
			stringstream ss;
			ss << pool_->patid << ": Freeing a " << name_ << " pool";
			glog.msg(ss.str());
		}
		pool_->free(pools_.back());
		pools_.pop_back();
		curPool_--;
		assert_gt(lastCurInPool_.size(), 0);
		cur_ = lastCurInPool_.back();
		lastCurInPool_.pop_back();
	}

	bowtieChunkPool*      pool_;
	const char     *name_;
	std::vector<T*> pools_; /// the memory pools
	uint32_t        curPool_; /// pool we're current allocating from
	std::vector<uint32_t> lastCurInPool_;
	uint32_t        lim_;  /// # elements held in pool_
	uint32_t        cur_;  /// index of next free element of pool_
};

#endif /* POOL_H_ */