-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathASDP_BufferPool.h
More file actions
66 lines (52 loc) · 2.24 KB
/
Copy pathASDP_BufferPool.h
File metadata and controls
66 lines (52 loc) · 2.24 KB
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
/*
* Copyright (C) 2024: Arizona Board of Regents on Behalf of the University of Arizona
*/
#pragma once
/**
* @file ASDP_BufferPool.h
* @brief Apache Strap-Down Pilotage utility class to provide a pre-allocated pool of buffers.
*
* @author ReliaSolve.
* @date March 14, 2024.
*/
#include <vector>
#include <list>
#include <memory>
#include <mutex>
#include <cstdint>
#include <string>
#include <atomic>
namespace asdp {
/// @brief Manages a thread-safe pre-allocated pool of buffers.
class BufferPool {
public:
/// @brief Constructs a buffer pool with the given buffer size and initial number of buffers.
/// @param bufferSize The size of each buffer in bytes.
/// @param bufferCount The initial number of buffers in the pool.
BufferPool(size_t bufferSize, size_t bufferCount);
/// @brief Destroys the buffer pool after waiting for all outstanding buffers to return to the pool.
~BufferPool();
/// @brief Returns a buffer from the pool, or nullptr if the pool is being destroyed.
/// @details Returns a buffer from the pool, creating a new buffer if necessary.
/// When the shared_ptr is destroyed, the buffer is automatically returned to the pool.
/// The nullptr is returned if the pool is being destroyed.
/// This method is thread-safe.
/// @return A buffer from the pool, or nullptr if the pool is being destroyed.
std::shared_ptr<std::vector<uint8_t>> GetBuffer();
/// @brief Test the BufferPool class.
/// @return Empty string on success, descriptive error message on failure.
static std::string Test();
private:
/// The size of each buffer in bytes.
size_t m_bufferSize;
/// A list of all buffers thave have been allocated, whether they are free or have been loaned out.
std::list< std::vector<uint8_t> > m_allBuffers;
/// A list of pointers to buffers that are free (have not been loaned out).
std::list< std::vector<uint8_t>* > m_freeBuffers;
/// Mutex to guard access to our data structures to make this class thread-safe.
std::mutex mtx;
/// Set to true when we're in the process of destroying the pool. Prevents new
/// buffers from being allocated.
std::atomic_bool m_done;
};
}