Add test for releasing connections back to the server

This commit is contained in:
2025-08-22 13:10:26 -04:00
parent 7860e720bd
commit 1a85e91113
9 changed files with 168 additions and 42 deletions

View File

@@ -1,5 +1,6 @@
#include "connection_registry.hpp"
#include "connection.hpp"
#include <atomic>
#include <cstring>
#include <stdexcept>
#include <unistd.h>
@@ -19,7 +20,7 @@ ConnectionRegistry::ConnectionRegistry() : connections_(nullptr), max_fds_(0) {
// Allocate virtual address space using mmap
// MAP_ANONYMOUS provides zero-initialized pages on-demand (lazy allocation)
connections_ = static_cast<Connection **>(
connections_ = static_cast<std::atomic<Connection *> *>(
mmap(nullptr, aligned_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
@@ -34,7 +35,7 @@ ConnectionRegistry::ConnectionRegistry() : connections_(nullptr), max_fds_(0) {
ConnectionRegistry::~ConnectionRegistry() {
if (connections_ != nullptr) {
for (size_t fd = 0; fd < max_fds_; ++fd) {
delete connections_[fd];
delete connections_[fd].load(std::memory_order_relaxed);
}
if (munmap(connections_, aligned_size_) == -1) {
perror("munmap");
@@ -47,16 +48,13 @@ void ConnectionRegistry::store(int fd, std::unique_ptr<Connection> connection) {
abort();
}
// Release ownership from unique_ptr and store raw pointer
connections_[fd] = connection.release();
connections_[fd].store(connection.release(), std::memory_order_release);
}
std::unique_ptr<Connection> ConnectionRegistry::remove(int fd) {
if (fd < 0 || static_cast<size_t>(fd) >= max_fds_) {
abort();
}
Connection *conn = connections_[fd];
connections_[fd] = nullptr;
// Transfer ownership back to unique_ptr
return std::unique_ptr<Connection>(conn);
return std::unique_ptr<Connection>(
connections_[fd].exchange(nullptr, std::memory_order_acquire));
}