内存池---c语言实现

内存池是一种为了避免cpu多次申请小块内存而节省cpu资源的技术。内存池预先申请一定数量的、容量相等的内存块。当需要使用内存时,从内存池中分出一部分内存块。内存池可以使得内存的分配效率提高。

这里先写一个简单的内存池。

第一部分内存池头文件

#ifndef THREADPOOL_H
#define THREADPOOL_H

#include "queue.h"

//线程池结构
typedef struct {
    int thread_num;            //线程池中线程的数量
    pthread_t *tid_arr;        //线程池中线程id的数组
    pQueue services_pq;        //线程池的服务请求队列
}ThreadPool_t;

int threadpool_init(int num, void *(*pfunc)(void*), void *arg);
int threadpool_destroy();    //销毁线程池

int threadpool_add_services(struct s_t *msg);    //向服务请求队列中添加服务请求

int threadpool_get_services(struct s_t *msg);    //从服务请求队列中取出服务请求

#endif
第二部分内存池实现 .c 文件

#include "ThreadPool.h"

static ThreadPool_t *pool = NULL;

int threadpool_init(int num, void *(*pfunc)(void*), void *arg)
{//num:线程池中线程的个数
 //pfunc:线程池中线程的入口函数
 //arg:pfunc的参数
    if ( pool != NULL ) {
        return -1;//表示线程池已经被创建
    }
    pool = malloc(sizeof(ThreadPool_t));
    pool->thread_num = num;
    pool->tid_arr = malloc(num*sizeof(pthread_t));
    pool->services_pq = init_queue();

    int i;
    for ( i=0; i<num; i++) {
        pthread_create(&pool->tid_arr[i], NULL, pfunc, arg);    
    }

    return 0;
}

int threadpool_destroy()    //销毁线程池
{
    int i;
    if ( pool == NULL ) {
        return -1;
    }

    for ( i=0; i<pool->thread_num; i++) {
        pthread_cancel(pool->tid_arr[i]);
    }
    destroy_queue(pool->services_pq);
    free(pool->tid_arr);
    free(pool);
    pool = NULL;
    return 0;
}

int threadpool_add_services(struct s_t *msg)    //向服务请求队列中添加服务请求
{
    if ( pool == NULL ) {
        return -1;
    }
    en_queue(pool->services_pq, *msg);
    return 0;
}

int threadpool_get_services(struct s_t *msg)    //从服务请求队列中取出服务请求
{
    if ( pool == NULL ) {
        return -1;
    }
    de_queue(pool->services_pq, msg);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值