This commit is contained in:
trung09122002
2026-09-18 18:14:42 +07:00
commit 48bd5377dc
224 changed files with 37685 additions and 0 deletions

View File

@@ -0,0 +1,92 @@
#ifndef VSLAM_BUFFER_POOL_H
#define VSLAM_BUFFER_POOL_H
// Pool tai su dung buffer, de chuoi perception khong cap phat gi o trang thai
// on dinh.
//
// Chuoi hien tai moi khung sinh: cloud_raw (320x240 = 76800 diem) ->
// cloud_filtered -> cloud_aligned. Neu moi buoc malloc mot vector moi thi o
// 10 Hz la ~9 MB/s di qua allocator, va tren Jetson dieu do the hien thanh
// jitter chu khong phai thong luong.
//
// Cach dung: hai buffer luan phien, 0 malloc o trang thai on dinh.
// Acquire() tra shared_ptr co deleter tu tra ve pool. Neu pool da bi huy
// truoc object thi deleter xoa that -- an toan khi tat may.
//
// allocated() ra /api/status: con so nay khong duoc tang sau khi he chay on
// dinh. Tang nghia la co cho giu shared_ptr lau hon can (ro ri thuc su, hoac
// mot Channel capacity qua lon).
#include <atomic>
#include <cstddef>
#include <memory>
#include <mutex>
#include <vector>
namespace vslam {
template <typename T>
class BufferPool : public std::enable_shared_from_this<BufferPool<T>> {
public:
// max_idle: giu toi da bao nhieu buffer roi. Vuot qua thi tra buffer se xoa
// that thay vi giu -- tranh pool phinh vinh vien sau mot dot tai cao.
static std::shared_ptr<BufferPool<T>> Create(size_t max_idle = 4) {
return std::shared_ptr<BufferPool<T>>(new BufferPool<T>(max_idle));
}
std::shared_ptr<T> Acquire() {
std::unique_ptr<T> obj;
{
std::lock_guard<std::mutex> lk(mu_);
if (!idle_.empty()) {
obj = std::move(idle_.back());
idle_.pop_back();
}
}
if (!obj) {
obj = std::make_unique<T>();
allocated_.fetch_add(1, std::memory_order_relaxed);
}
// weak_ptr: neu pool chet truoc object thi deleter xoa that.
std::weak_ptr<BufferPool<T>> weak = this->shared_from_this();
T* raw = obj.release();
return std::shared_ptr<T>(raw, [weak](T* p) {
if (auto pool = weak.lock()) {
pool->Release(std::unique_ptr<T>(p));
} else {
delete p;
}
});
}
size_t idle() const {
std::lock_guard<std::mutex> lk(mu_);
return idle_.size();
}
size_t allocated() const { return allocated_.load(std::memory_order_relaxed); }
void Clear() {
std::lock_guard<std::mutex> lk(mu_);
idle_.clear();
}
private:
explicit BufferPool(size_t max_idle) : max_idle_(max_idle) {}
void Release(std::unique_ptr<T> obj) {
std::lock_guard<std::mutex> lk(mu_);
if (idle_.size() >= max_idle_) return; // xoa that
idle_.push_back(std::move(obj));
}
const size_t max_idle_;
mutable std::mutex mu_;
std::vector<std::unique_ptr<T>> idle_;
std::atomic<size_t> allocated_{0};
};
} // namespace vslam
#endif // VSLAM_BUFFER_POOL_H