This repository has been archived on 2025-09-14. You can view files and clone it, but cannot push or open issues or pull requests.
Files
stellar-stellar/infra/session_manager/session_pool.c

106 lines
2.2 KiB
C

#include <assert.h>
#include <stdlib.h>
#include "session_internal.h"
#include "session_pool.h"
struct session_pool
{
uint64_t capacity;
uint64_t used;
uint64_t free;
struct session_queue free_list;
};
struct session_pool *session_pool_new(uint64_t capacity)
{
struct session_pool *pool = (struct session_pool *)calloc(1, sizeof(struct session_pool) + capacity * sizeof(struct session));
if (pool == NULL)
{
return NULL;
}
pool->used = 0;
pool->free = 0;
pool->capacity = capacity;
TAILQ_INIT(&pool->free_list);
struct session *array = (struct session *)(pool + 1);
for (uint64_t i = 0; i < capacity; i++)
{
struct session *sess = &array[i];
TAILQ_INSERT_TAIL(&pool->free_list, sess, free_tqe);
pool->free++;
}
return pool;
}
void session_pool_free(struct session_pool *pool)
{
if (pool)
{
struct session *sess;
while ((sess = TAILQ_FIRST(&pool->free_list)))
{
TAILQ_REMOVE(&pool->free_list, sess, free_tqe);
pool->free--;
}
assert(pool->free == 0);
assert(pool->used == 0);
free(pool);
pool = NULL;
}
}
struct session *session_pool_acquire_sessoin(struct session_pool *pool)
{
if (pool == NULL)
{
return NULL;
}
struct session *sess = TAILQ_FIRST(&pool->free_list);
if (sess)
{
TAILQ_REMOVE(&pool->free_list, sess, free_tqe);
pool->free--;
pool->used++;
}
return sess;
}
void session_pool_release_sessoin(struct session_pool *pool, struct session *sess)
{
if (pool == NULL || sess == NULL)
{
return;
}
TAILQ_INSERT_TAIL(&pool->free_list, sess, free_tqe);
pool->free++;
pool->used--;
}
const struct session *session_pool_get0(const struct session_pool *pool, uint64_t idx)
{
if (pool == NULL || idx >= pool->capacity)
{
return NULL;
}
struct session *array = (struct session *)(pool + 1);
return &array[idx];
}
uint64_t session_pool_get_free_num(const struct session_pool *pool)
{
return pool->free;
}
uint64_t session_pool_get_used_num(const struct session_pool *pool)
{
return pool->used;
}