内存池---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         pthread_create(&pool->tid_arr[i], NULL, pfunc, arg);    
    }

    return 0;
}

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

    for ( i=0; ithread_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;
}

你可能感兴趣的:(C语言,计算机基础,c语言,开发语言)