百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

一个简单实用的线程池及线程池组的实现!

ccwgpt 2024-10-01 08:17 22 浏览 0 评论

1.线程池简介

线程池,顾名思义,就是一个“池子”里面放有多个线程。为什么要使用线程池呢?当我们编写的代码需要并发异步处理很多任务时候,一般的处理办法是一个任务开启一个线程去处理,处理结束后释放线程。可是这样频繁的申请释放线程,系统的开销很大,为了解决这个问题,线程池就产生了。线程池实现原理是事先申请一定数量的线程存放在程序中,当外部有任务需要线程处理时,把这个任务放到这个“池子”里面,“池子”里面空闲的线程就去取这个任务进行处理,这样既能实现多线程并发处理任务,又能减少系统频繁创建删除线程的开销,这种技术叫做池化技术,相应的池化技术还有内存池、连接池等。

为了更形象理解线程池,举一个例子:线程池就像鸡圈里面鸡,每一个鸡比作一个线程,你手里有一把玉米,每一个颗玉米比作一个任务,鸡吃玉米比作处理任务。当你把一把玉米撒入鸡圈,一群鸡就围过来抢玉米,但是一次一只鸡只能吃一颗玉米,吃完一颗继续吃下一颗,直到鸡圈里面的玉米吃完才停止。线程池处理任务也是一样的,当任务链表上有任务时,通过条件变量通知线程池里面的线程,一群线程就围过来了,但是一个线程一次只能取一个任务进行处理,处理完又去取下一个任务,池子里面每一个线程都是这样处理,直到链表上面的任务全部处理完了,池子中的线程又空闲起来了。

2.线程池-设计实现

实现思路:通过向系统申请多个线程,创建一个任务链表,链表上面存放待处理的任务,当有新的任务加入时候,通过条件变量通知池子里面的线程从链表上面取任务,然后处理任务,一直这样循环下去。

首先定义结构体,定义如下:

/**
 * 定义的回调函数
*/
typedef void (*task_func_t)(void *args);

/**
 * 定义的任务节点结构体
*/
typedef struct task_t
{
    void             *args; //任务参数
    task_func_t      func;  //任务函数指针
    struct list_head node;  //链表节点
}task_t;

/**
 * 线程池信息
*/
typedef struct threadpool_t
{
    struct list_head hlist;       //任务链表
    int              thread_num;  //线程池数量
    int              max_ts_num;  //最大任务数量
    volatile int     curr_ts_num; //当前线程池存在的任务数
    volatile int     is_exit;     //是否退出线程池标志
    pthread_mutex_t  mutex;       //互斥锁
    pthread_cond_t   cond;        //条件变量
    pthread_t        *ths;        //线程id数组
}threadpool_t;

这是线程池实现的程序:


/**
 * @brief:线程处理任务函数
 * @args: 传入的参数
 * @return: NULL
*/
static void* _process_task_thread(void *args)
{
    threadpool_t* tp = (threadpool_t*)args;
    struct list_head *pos = NULL;
    task_t *task=NULL;

    if(!args) return NULL;

    while(1)
    {
        pthread_mutex_lock(&tp->mutex);
        while(list_empty(&tp->hlist) && !tp->is_exit){
            pthread_cond_wait(&tp->cond, &tp->mutex);
        }
        if(tp->is_exit){        //判断释放退出线程池
            pthread_mutex_unlock(&tp->mutex);
            break;
        }
        pos = tp->hlist.next;   //从任务链表取出头节点
        list_del(pos);          //从链表中删除节点
        --tp->curr_ts_num;      //更新任务数
        pthread_mutex_unlock(&tp->mutex);

        task = list_entry(pos, task_t, node); //从链表节点推出任务节点
        task->func(task->args); //执行任务
        free(task);             //释放任务内存
    }

    return NULL;
}

/**
 * @brief:创建一个线程池
 * @thread_nums: 线程数量
 * @max_ts_num:线程池中最大的任务数量
 * @return: 线程池句柄
*/
threadpool_t* create_threadpool(int thread_nums, int max_ts_num)
{
    if(thread_nums <= 0) return NULL;

    threadpool_t* tp = (threadpool_t*)malloc(sizeof(threadpool_t));
    memset(tp, 0, sizeof(threadpool_t));
    INIT_LIST_HEAD(&tp->hlist);

    tp->is_exit = 0;
    tp->curr_ts_num = 0;
    tp->thread_num = thread_nums;
    tp->max_ts_num = max_ts_num;

    tp->ths = (pthread_t*)malloc(sizeof(pthread_t)*thread_nums);
    pthread_mutex_init(&tp->mutex, NULL);
    pthread_cond_init(&tp->cond, NULL);

    for(int i=0; i<tp->thread_num; ++i){
        pthread_create(&(tp->ths[i]), NULL, _process_task_thread, tp);
    }

    return tp;
}   

/**
 * @brief:往线程池中添加任务
 * @tp: 线程池句柄
 * @func:任务处理函数指针
 * @args:传入任务参数
 * @priority: 优先级 1:优先处理 其他:添加到尾部
 * @return: 返回状态 0:ok
*/
int add_task_threadpool(threadpool_t* tp, task_func_t func, void *args, int priority)
{
    if(!tp) return -1;
    if(!func) return -2;
    if(tp->curr_ts_num > tp->max_ts_num) return -3;

    task_t *task = (task_t*)malloc(sizeof(task_t)); //申请任务节点内存
    task->func = func; //给函数指针赋值
    task->args = args; //保持参数指针

    pthread_mutex_lock(&tp->mutex);
    if(priority==1)    //高优先级,添加到头部
        list_add(&task->node, &tp->hlist);
    else               //添加到尾部
        list_add_tail(&task->node, &tp->hlist);
    ++tp->curr_ts_num; //更新任务数
    pthread_mutex_unlock(&tp->mutex);

    pthread_cond_signal(&tp->cond); //通知线程取任务

    return 0;
}

/**
 * @brief:获取线程池中当前存在的任务数量
 * @tp: 线程池句柄
 * @return: 当前任务数量
*/
int get_ts_num_threadpool(threadpool_t* tp)
{
    return tp ? tp->curr_ts_num : -1;
}

/**
 * @brief:释放线程池资源
 * @tp:线程池句柄
 * @return: 0:ok
*/
int destory_threadpool(threadpool_t* tp)
{
    if(!tp) return -1;
    while(!list_empty(&tp->hlist)){  //等待线程池执行完链表中的任务
        continue;   
    }
    tp->is_exit = 1;                  //更新标志,退出线程池
    pthread_cond_broadcast(&tp->cond);//通知所有线程函数

    for(int i=0; i<tp->thread_num; ++i){//等待所有线程函数结束
        pthread_join(tp->ths[i], NULL);
    }

    pthread_mutex_destroy(&tp->mutex); //释放资源
    pthread_cond_destroy(&tp->cond);
    
    free(tp->ths);

    free(tp);
    tp = NULL;

    return 0;
}

相关视频推荐

手把手实现线程池(120行),实现异步操作,解决项目性能问题

手撕高性能线程池,准备好linux开发环境

线程池在3个开源框架的应用(redis、skynet、workflow)

免费学习地址:c/c++ linux服务器开发/后台架构师

需要C/C++ Linux服务器架构师学习资料加qun812855908获取(资料包括C/C++,Linux,golang技术,Nginx,ZeroMQ,MySQL,Redis,fastdfs,MongoDB,ZK,流媒体,CDN,P2P,K8S,Docker,TCP/IP,协程,DPDK,ffmpeg等),免费分享

3.线程池组-设计实现

有了线程池处理并发任务,为什么还要线程池组呢?原因在于线程池中,所有的线程都使用一个互斥锁阻塞,当你创建的线程池中线程的个数比较多的情况下,存在很多线程对同一个线程抢占,这样会影响线程池取任务处理的效率。因此由"小颗粒"(即每一个线程池中线程个数少)的线程池组成一个"线程池组"这样就能减轻多个线程对同一个锁抢占造成效率低的问题。

设计实现:将多个线程池封装组合到一起,当外部有任务需要处理时,找到线程池组中线程池任务最少的池子,把任务给放进去。

?定义一个线程池组管理结构体:

typedef struct manange_thpool_t
{
    int thpool_nums;                            //线程池个数
    threadpool_t *thpools[MAX_THREADPOOL_NUMS]; //线程池结构体
}manange_thpool_t;

代码实现:


/**
 * @brief:创建线程池组管理句柄
 * @tp_nums:线程池组中线程池个数
 * @thread_num:单个线程池中线程个数
 * @max_ts_n:单个线程池中最大的任务数量
*/
manange_thpool_t* create_group_threadpool(int tp_nums, int thread_num, int max_ts_n)
{
    manange_thpool_t* mtp = (manange_thpool_t*)malloc(sizeof(manange_thpool_t));
    if(!mtp) return NULL;
    memset(mtp, 0, sizeof(manange_thpool_t));
    mtp->thpool_nums = tp_nums;

    for(int i=0; i<tp_nums; ++i){
        mtp->thpools[i] = create_threadpool(thread_num, max_ts_n);
    }

    return mtp;
}

/**
 * @brief:往线程池组中添加任务
 * @mtp:线程池组句柄
 * @func:任务函数
 * @args:任务函数的参数
 * @priority: 优先级 1:优先处理 其他:依次处理
 * @return: 0:ok 其他:err
*/
int add_task_group_threadpool(manange_thpool_t* mtp, task_func_t func, void *args, int priority)\
{
    int ts_num= INT_MAX;
    threadpool_t *tp=NULL;
    int index=0;

    for(register int i=0; i<mtp->thpool_nums; ++i){
        if(mtp->thpools[i]->curr_ts_num < ts_num){
            ts_num = mtp->thpools[i]->curr_ts_num;
            tp = mtp->thpools[i];
            index=i;
        }
    }

    if(!tp){
        tp = mtp->thpools[0];
    }
    return add_task_threadpool(tp, func, args, priority);
}

/**
 * @brief:释放线程池组函数
 * @tp: 线程池组句柄
 * @return:none
*/
void destory_group_threadpool(manange_thpool_t* tp)
{
    if(!tp) return;
    
    for(int i=0; i<tp->thpool_nums; ++i){
        if(tp->thpools[i]) destory_threadpool(tp->thpools[i]);
    }
}

4.测试

测试程序如下:


#include <stdio.h>
#include <unistd.h>
#include "list.h"
#include "threadpool.h"
#include "manange_threadpool.h"

//任务传递的参数
typedef struct info_t
{
    int times;
    char buffer[32];
}info_t;


void task1(void *args)
{
    info_t *info = (info_t*)args;
    printf("handle task1 pid=%lld times=%d buffer=%s\n", pthread_self(), info->times, info->buffer);
    free(args);
}

void task2(void *args)
{
    info_t *info = (info_t*)args;
    printf("handle task2 pid=%lld times=%d buffer=%s\n", pthread_self(), info->times, info->buffer);
    free(args);
}

void task3(void *args)
{
    info_t *info = (info_t*)args;
    printf("handle task3 pid=%lld times=%d buffer=%s\n", pthread_self(), info->times, info->buffer);
    free(args);
}

//------------split-----------------

void test_threadpool(void)
{
    threadpool_t* tp = create_threadpool(4, 128);

    info_t *info;

    for(int t=0; t<10; ++t){
        for(int i=0; i<32; ++i){
            info = (info_t *)malloc(sizeof(info_t));
            info->times=i;
            sprintf(info->buffer, "Test ThreadPool task1 info...");
            add_task_threadpool(tp, task1, info, 1); //往线程池组添加任务

            info = (info_t *)malloc(sizeof(info_t));
            info->times=i;
            sprintf(info->buffer, "Test ThreadPool task2 info...");
            add_task_threadpool(tp, task2, info, 0);

            info = (info_t *)malloc(sizeof(info_t));
            info->times=i;
            sprintf(info->buffer, "Test ThreadPool task3 info...");
            add_task_threadpool(tp, task3, info, 0);
        }
        sleep(1);
    }

    destory_threadpool(tp);
    printf("Test ThreadPool Finish...\n");
}

void test_manange_threadpool(void)
{
    //创建线程池组句柄,有4个线程池,每个线程池使用4线程,每个线程池最大的任务数是32
    manange_thpool_t* mtp = create_group_threadpool(4, 4, 128);
    info_t *info;

    for(int t=0; t<10; ++t){
        for(int i=0; i<32; ++i){
            info = (info_t *)malloc(sizeof(info_t));
            info->times=i;
            sprintf(info->buffer, "Test task1 info...");
            add_task_group_threadpool(mtp, task1, info, 1); //往线程池组添加任务

            info = (info_t *)malloc(sizeof(info_t));
            info->times=i;
            sprintf(info->buffer, "Test task2 info...");
            add_task_group_threadpool(mtp, task2, info, 0);

            info = (info_t *)malloc(sizeof(info_t));
            info->times=i;
            sprintf(info->buffer, "Test task3 info...");
            add_task_group_threadpool(mtp, task3, info, 0);
        }
        sleep(1);
    }

    //释放线程池组资源
    destory_group_threadpool(mtp);
    printf("Test Manage ThreadPool Finish...\n");
}

int main(void)
{

#if 1 //测试单个的线程池功能
    test_threadpool();
#else //测试线程池组功能
    test_manange_threadpool();
#endif

    return 0;
}

通过修改宏定义,决定使用线程池还是线程池组

  1. 测试线程池结果

?2.测试线程池组结果

5.总结

使用线程池情况:一般程序中有并发处理任务,但是处理的任务并发量不高时候采用线程池。

使用线程池组情况:程序中任务并发量很大情况下使用。

相关推荐

如何为Hadoop选择最佳弹性MapReduce框架

ZDNet至顶网服务器频道07月22日新闻消息:亚马逊Web服务的弹性MapReduce是一项基于Hadoop的实施,它可允许你运行大型的预处理工作,如格式转换和数据聚合等。虽然我们可以选择很多的...

《平安小猪》:J.K.罗琳用“魔法”放大的真实

对很多孩子来说,某些玩具是抚慰心灵的“忠实伙伴”,几乎无可替代。J.K.罗琳在看到儿子大卫对玩偶小猪的依恋后创作了“平安小猪”的故事,这也是她自《哈利·波特》之后创作的首部儿童长篇小说。男孩杰克在平安...

一页纸精华 | HDFS

要入门大数据,最好的办法就是理清hadoop的生态系统。本期为你介绍分布式文件系统HDFS。ApacheHadoop2.0生态系统如下图所示:Hadoop2.0生态系统图Hadoop核心项目包括:H...

谷歌搁置与法国出版商的协议,将等候反垄断裁定

据路透社6月29日消息,两位知情消息人士称,谷歌搁置了与一些法国出版商达成的为新闻内容付费的初步协议,将等待反垄断审议结果。该决定可能为欧洲在线新闻的版权谈判定下基调。文件显示,按照谷歌与法国新闻总联...

Java 微服务从源码实战开始 | Gitee 项目推荐

在软件开发的不同时期、阶段,对技术架构的理解、选择和应用都有着不一样的诉求。微服务架构是当前互联网业界的一个技术热点,它的思想也更符合我们的目标:根据业务模块划分服务种类。每个服务可以独立部署并且互相...

快讯|谷歌搁置向法国出版商付费协议:等待反垄断决定

财经网科技6月30日讯,据新浪科技消息,两位知情人士透露,谷歌已经搁置此前与一些法国出版商达成的为新闻内容付费的初步协议。因为谷歌正在等待一项反垄断决定,这项决定可能会为该公司的欧洲在线新闻版权谈判定...

外媒:谷歌搁置与法国出版商的协议 等候反垄断决定

路透中文网30日报道,据两位知情消息人士透露,谷歌GOOGL.O搁置了与一些法国出版商达成的为新闻内容付费的初步协议,等待一项反垄断决定。该决定可能为欧洲在线新闻的版权谈判定下基调。报道显示,根据路透...

大数据任务调度框架Oozie

Oozie(驯象人)是一个基于工作流引擎的开源框架,由Cloudera公司贡献给Apache,提供对HadoopMapReduce、PigJobs的任务调度与协调。Oozie需要部署到JavaS...

惊了!SpringBoot 3.4 触雷,升级后参数绑定竟悄悄破坏你的代码?

背景在微服务架构中,我们经常利用HTTP请求头来控制系统行为,比如实现灰度发布和流量控制。在PIG微服务框架中,我们通过重写SpringCloudLoadBalancer,根据请求he...

《终结者》:科幻电影巅峰的里程碑

在阅读此文之前,麻烦您点击一下“关注”,既方便您进行讨论和分享,又能给您带来不一样的参与感,感谢您的支持。文|庭芥摘要:本文以一位影评家的视角赏析詹姆斯·卡梅隆执导的经典科幻电影《终结者》。通过对该...

AI已经越过红线?复旦大学:在知道自己将被关闭后,AI复制了自己

2024年12月9日,复旦大学的一项研究引发了全球科技界的强烈关注。研究团队对Meta与阿里巴巴旗下的两个大型AI系统展开测试,结果发现,在知晓自身可能被关闭的情况下,它们居然选择自我复制。这不是普通...

重磅开源!LocalAI让你在个人电脑上运行AI大模型,无需显卡,已获28K Star!

随着AI技术的快速发展,如何在本地设备上高效运行AI模型成为了开发者关注的焦点。LocalAI开源项目提供了一个革命性的解决方案-它让用户能够在个人电脑上轻松部署和运行各种AI模型,并且完全兼容...

了解《终结者》的恐怖末日世界观,能让你看懂《终结者6》

相信很多人的科幻动作启蒙片,应该就是《终结者》系列,起码对于我来说,童年的暑假里,不止一次反复看着《终结者2》的电影,深深被影片中施瓦辛格的硬核铁汉形象吸引,也为片中的液态机器人着迷。《终结者》系列成...

Golang底层是用什么语言编写的?

Go底层语言Go语言在1.5版本之前主要由汇编和C语言写的,C语言占比85%以上,另外有少量的周边模块如文档等,带了些htmlshellperl代码,可以忽略不计。1.5版本及之后...

skynet服务的缺陷 lua死循环

服务端高级架构—云风的skynet这边有一个关于云风skynet的视频推荐给大家观看点击就可以观看了!skynet是一套多人在线游戏的轻量级服务端框架,使用C+Lua开发。skynet的显著优点是,...

取消回复欢迎 发表评论: