diff --git a/src/section_list.c b/src/section_list.c index 2c74754..e1620e0 100644 --- a/src/section_list.c +++ b/src/section_list.c @@ -16,6 +16,7 @@ #include "user_list.h" #include #include +#include #include #include #include @@ -78,6 +79,9 @@ typedef struct article_block_pool_t ARTICLE_BLOCK_POOL; static char article_block_shm_name[FILE_NAME_LEN]; static ARTICLE_BLOCK_POOL *p_article_block_pool = NULL; +/* Spinlock for protecting free list operations */ +static pthread_spinlock_t free_list_spinlock; + static char section_list_shm_name[FILE_NAME_LEN]; SECTION_LIST_POOL *p_section_list_pool = NULL; @@ -102,6 +106,13 @@ int article_block_init(const char *filename, int block_count) return -1; } + /* Initialize spinlock for free list protection */ + if (pthread_spin_init(&free_list_spinlock, PTHREAD_PROCESS_PRIVATE) != 0) + { + log_error("pthread_spin_init error"); + return -1; + } + if (block_count <= 0 || block_count > ARTICLE_BLOCK_PER_POOL) { log_error("article_block_count exceed limit %d", ARTICLE_BLOCK_PER_POOL); @@ -310,6 +321,9 @@ int detach_article_block_shm(void) p_article_block_pool = NULL; + /* Destroy spinlock */ + pthread_spin_destroy(&free_list_spinlock); + return 0; } @@ -317,6 +331,8 @@ inline static ARTICLE_BLOCK *pop_free_article_block(void) { ARTICLE_BLOCK *p_block = NULL; + pthread_spin_lock(&free_list_spinlock); + if (p_article_block_pool->p_block_free_list != NULL) { p_block = p_article_block_pool->p_block_free_list; @@ -325,13 +341,19 @@ inline static ARTICLE_BLOCK *pop_free_article_block(void) p_block->article_count = 0; } + pthread_spin_unlock(&free_list_spinlock); + return p_block; } inline static void push_free_article_block(ARTICLE_BLOCK *p_block) { + pthread_spin_lock(&free_list_spinlock); + p_block->p_next_block = p_article_block_pool->p_block_free_list; p_article_block_pool->p_block_free_list = p_block; + + pthread_spin_unlock(&free_list_spinlock); } int article_block_reset(void)