#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 #include #include #include #include namespace vslam { template class BufferPool : public std::enable_shared_from_this> { 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> Create(size_t max_idle = 4) { return std::shared_ptr>(new BufferPool(max_idle)); } std::shared_ptr Acquire() { std::unique_ptr obj; { std::lock_guard lk(mu_); if (!idle_.empty()) { obj = std::move(idle_.back()); idle_.pop_back(); } } if (!obj) { obj = std::make_unique(); allocated_.fetch_add(1, std::memory_order_relaxed); } // weak_ptr: neu pool chet truoc object thi deleter xoa that. std::weak_ptr> weak = this->shared_from_this(); T* raw = obj.release(); return std::shared_ptr(raw, [weak](T* p) { if (auto pool = weak.lock()) { pool->Release(std::unique_ptr(p)); } else { delete p; } }); } size_t idle() const { std::lock_guard lk(mu_); return idle_.size(); } size_t allocated() const { return allocated_.load(std::memory_order_relaxed); } void Clear() { std::lock_guard lk(mu_); idle_.clear(); } private: explicit BufferPool(size_t max_idle) : max_idle_(max_idle) {} void Release(std::unique_ptr obj) { std::lock_guard 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> idle_; std::atomic allocated_{0}; }; } // namespace vslam #endif // VSLAM_BUFFER_POOL_H