一个Linux下C线程池的实现

线程池(C/C++版) C/C++ threadpool封装, 线程池, Linux, 多线程, pthread 立即下载
什么时候需要创建线程池呢?简单的说,如果一个应用需要频繁的创建和销毁线程,而任务执行的时间又非常短,这样线程创建和销毁的带来的开销就不容忽视,这时也是线程池该出场的机会了。如果线程创建和销毁时间相比任务执行时间可以忽略不计,则没有必要使用线程池了。

下面是Linux系统下用C语言创建的一个线程池。线程池会维护一个任务链表(每个CThread_worker结构就是一个任务)。

pool_init()函数预先创建好max_thread_num个线程,每个线程执thread_routine ()函数。该函数中

while (pool->cur_queue_size == 0)
{
      pthread_cond_wait (&(pool->queue_ready),&(pool->queue_lock));
}
表示如果任务链表中没有任务,则该线程出于阻塞等待状态。否则从队列中取出任务并执行。


pool_add_worker()函数向线程池的任务链表中加入一个任务,加入后通过调用pthread_cond_signal (&(pool->queue_ready))唤醒一个出于阻塞状态的线程(如果有的话)。

pool_destroy ()函数用于销毁线程池,线程池任务链表中的任务不会再被执行,但是正在运行的线程会一直把任务运行完后再退出。

   

下面贴出完整代码

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <pthread.h> 
#include <assert.h> 

/* 
*线程池里所有运行和等待的任务都是一个CThread_worker 
*由于所有任务都在链表里,所以是一个链表结构 
*/ 
typedef struct worker 
{ 
    /*回调函数,任务运行时会调用此函数,注意也可声明成其它形式*/ 
    void *(*process) (void *arg); 
    void *arg;/*回调函数的参数*/ 
    struct worker *next; 

} CThread_worker; 

/*线程池结构*/ 
typedef struct 
{ 
    pthread_mutex_t queue_lock; 
    pthread_cond_t queue_ready; 

    /*链表结构,线程池中所有等待任务*/ 
    CThread_worker *queue_head; 

    /*是否销毁线程池*/ 
    int shutdown; 
    pthread_t *threadid; 
    /*线程池中允许的活动线程数目*/ 
    int max_thread_num; 
    /*当前等待队列的任务数目*/ 
    int cur_queue_size; 

} CThread_pool; 

int pool_add_worker (void *(*process) (void *arg), void *arg); 
void *thread_routine (void *arg); 

static CThread_pool *pool = NULL; 
void pool_init (int max_thread_num) 
{ 
    pool = (CThread_pool *) malloc (sizeof (CThread_pool)); 

    pthread_mutex_init (&(pool->queue_lock), NULL); 
    pthread_cond_init (&(pool->queue_ready), NULL); 

    pool->queue_head = NULL; 

    pool->max_thread_num = max_thread_num; 
    pool->cur_queue_size = 0; 

    pool->shutdown = 0; 

    pool->threadid = 
        (pthread_t *) malloc (max_thread_num * sizeof (pthread_t)); 
    int i = 0; 
    for (i = 0; i < max_thread_num; i++) 
    {  
        pthread_create (&(pool->threadid[i]), NULL, thread_routine, 
                NULL); 
    } 
} 

/*向线程池中加入任务*/ 
int pool_add_worker (void *(*process) (void *arg), void *arg) 
{ 
    /*构造一个新任务*/ 
    CThread_worker *newworker = 
        (CThread_worker *) malloc (sizeof (CThread_worker)); 
    newworker->process = process; 
    newworker->arg = arg; 
    newworker->next = NULL;/*别忘置空*/ 

    pthread_mutex_lock (&(pool->queue_lock)); 
    /*将任务加入到等待队列中*/ 
    CThread_worker *member = pool->queue_head; 
    if (member != NULL) 
    { 
        while (member->next != NULL) 
            member = member->next; 
        member->next = newworker; 
    } 
    else 
    { 
        pool->queue_head = newworker; 
    } 

    assert (pool->queue_head != NULL); 

    pool->cur_queue_size++; 
    pthread_mutex_unlock (&(pool->queue_lock)); 
    /*好了,等待队列中有任务了,唤醒一个等待线程; 
    注意如果所有线程都在忙碌,这句没有任何作用*/ 
    pthread_cond_signal (&(pool->queue_ready)); 
    return 0; 
} 

/*销毁线程池,等待队列中的任务不会再被执行,但是正在运行的线程会一直 
把任务运行完后再退出*/ 
int pool_destroy () 
{ 
    if (pool->shutdown) 
        return -1;/*防止两次调用*/ 
    pool->shutdown = 1; 

    /*唤醒所有等待线程,线程池要销毁了*/ 
    pthread_cond_broadcast (&(pool->queue_ready)); 

    /*阻塞等待线程退出,否则就成僵尸了*/ 
    int i; 
    for (i = 0; i < pool->max_thread_num; i++) 
        pthread_join (pool->threadid[i], NULL); 
    free (pool->threadid); 

    /*销毁等待队列*/ 
    CThread_worker *head = NULL; 
    while (pool->queue_head != NULL) 
    { 
        head = pool->queue_head; 
        pool->queue_head = pool->queue_head->next; 
        free (head); 
    } 
    /*条件变量和互斥量也别忘了销毁*/ 
    pthread_mutex_destroy(&(pool->queue_lock)); 
    pthread_cond_destroy(&(pool->queue_ready)); 
     
    free (pool); 
    /*销毁后指针置空是个好习惯*/ 
    pool=NULL; 
    return 0; 
} 

void * thread_routine (void *arg) 
{ 
    printf ("starting thread 0x%x\n", pthread_self ()); 
    while (1) 
    { 
        pthread_mutex_lock (&(pool->queue_lock)); 
        /*如果等待队列为0并且不销毁线程池,则处于阻塞状态; 注意 
        pthread_cond_wait是一个原子操作,等待前会解锁,唤醒后会加锁*/ 
        while (pool->cur_queue_size == 0 && !pool->shutdown) 
        { 
            printf ("thread 0x%x is waiting\n", pthread_self ()); 
            pthread_cond_wait (&(pool->queue_ready), &(pool->queue_lock)); 
        } 

        /*线程池要销毁了*/ 
        if (pool->shutdown) 
        { 
            /*遇到break,continue,return等跳转语句,千万不要忘记先解锁*/ 
            pthread_mutex_unlock (&(pool->queue_lock)); 
            printf ("thread 0x%x will exit\n", pthread_self ()); 
            pthread_exit (NULL); 
        } 

        printf ("thread 0x%x is starting to work\n", pthread_self ()); 

        /*assert是调试的好帮手*/ 
        assert (pool->cur_queue_size != 0); 
        assert (pool->queue_head != NULL); 
         
        /*等待队列长度减去1,并取出链表中的头元素*/ 
        pool->cur_queue_size--; 
        CThread_worker *worker = pool->queue_head; 
        pool->queue_head = worker->next; 
        pthread_mutex_unlock (&(pool->queue_lock)); 

        /*调用回调函数,执行任务*/ 
        (*(worker->process)) (worker->arg); 
        free (worker); 
        worker = NULL; 
    } 
    /*这一句应该是不可达的*/ 
    pthread_exit (NULL); 
} 

下面是测试代码

void * myprocess (void *arg) 
{ 
    printf ("threadid is 0x%x, working on task %d\n", pthread_self (),*(int *)arg); 
    sleep (1);/*休息一秒,延长任务的执行时间*/ 
    return NULL; 
} 

int main (int argc, char **argv) 
{ 
    pool_init (3);/*线程池中最多三个活动线程*/ 
     
    /*连续向池中投入10个任务*/ 
    int *workingnum = (int *) malloc (sizeof (int) * 10); 
    int i; 
    for (i = 0; i < 10; i++) 
    { 
        workingnum[i] = i; 
        pool_add_worker (myprocess, &workingnum[i]); 
    } 
    /*等待所有任务完成*/ 
    sleep (5); 
    /*销毁线程池*/ 
    pool_destroy (); 

    free (workingnum); 
    return 0; 
}

将上述所有代码放入threadpool.c文件中,在Linux输入编译命令

$ gcc -o threadpool threadpool.c -lpthread

以下是运行结果

starting thread 0xb7df6b90
thread 0xb7df6b90 is waiting
starting thread 0xb75f5b90
thread 0xb75f5b90 is waiting
starting thread 0xb6df4b90
thread 0xb6df4b90 is waiting
thread 0xb7df6b90 is starting to work
threadid is 0xb7df6b90, working on task 0
thread 0xb75f5b90 is starting to work
threadid is 0xb75f5b90, working on task 1
thread 0xb6df4b90 is starting to work
threadid is 0xb6df4b90, working on task 2
thread 0xb7df6b90 is starting to work
threadid is 0xb7df6b90, working on task 3
thread 0xb75f5b90 is starting to work
threadid is 0xb75f5b90, working on task 4
thread 0xb6df4b90 is starting to work
threadid is 0xb6df4b90, working on task 5
thread 0xb7df6b90 is starting to work
threadid is 0xb7df6b90, working on task 6
thread 0xb75f5b90 is starting to work
threadid is 0xb75f5b90, working on task 7
thread 0xb6df4b90 is starting to work
threadid is 0xb6df4b90, working on task 8
thread 0xb7df6b90 is starting to work
threadid is 0xb7df6b90, working on task 9
thread 0xb75f5b90 is waiting
thread 0xb6df4b90 is waiting
thread 0xb7df6b90 is waiting
thread 0xb75f5b90 will exit
thread 0xb6df4b90 will exit
thread 0xb7df6b90 will exit


线程池实现,通过C语言实现 linux下通过200行C代码实现简单线程池,附源代码和文档说明: 200行C代码实现简单线程池.doc threadpool.c 立即下载

相关推荐

非常好用的C语言线程池,自己测试通过

自己写的非常好用的C语言线程,纯C代码,可以随便用。

线程池 c语言

本文旨在纯c实现线程池。线程池线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。

weixin_60208935的博客 4630

kettle信息发送钉钉

由于其他的作业比较多,想要在job中加入一个转化发送消息到钉钉,其他的配置说明直接获取系统的信息。这样也避免直接修改其他的转换和大量的工作量。 步骤: 1、新建一个转换 拉取获取系统信息、获取变量、JavaScript代码、获取access_token组件。 2、获取系统信息设置 拿到需要的信息,比如作业的读写更新删除行数,job的日志内容 这个日志内容同在作业执行页面下输出的日志,所以可以在执行作业时选择是详细日志、基本日志还是错误日志。 3、获取变量 获取变量主要是想要去拿到job的名称,文件名。按

Deng_7788的博客 1451

【线程系列之五】线程池介绍C语言

首先,定义一个包含线程池所需所有信息的结构体,如线程数组、任务队列、互斥锁、条件变量等。4// 任务队列节点void* arg;} task_t;// 线程池结构体// 线程数组// 保护任务队列的互斥锁// 任务队列的条件变量bool stop;// 线程池停止标志// 任务队列头指针// 任务队列尾指针// 当前活跃线程数// 最大活跃线程数(可配置)

qq_40604302的博客 1842

从零到千兆:KSZ9031 PHY芯片在Zynq PS端的驱动移植心路历程

本文详细记录了在Xilinx Zynq-7000平台(基于XC7Z020芯片)上,为KSZ9031千兆以太网PHY芯片移植LwIP协议栈驱动的完整过程。从硬件连接配置、Vivado工程设置到LwIP库的深度修改与调试,分享了解决PHY识别、自协商及性能优化等关键问题的实战经验,助力开发者实现稳定的千兆网络连接。

honey的博客 1117

鸿蒙实战开发教程-注册登录页面

在密码输入框中,只要设置TextInput的类型就可以实现带眼睛logo的密码输入框效果:

2401_82546228的博客 3564

【用C语言实现线程池】

用C语言实现线程池线程池原理线程池的组成结构任务队列工作的线程管理者线程代码实现 线程池原理   我们使用线程的时候就去创建一个线程,这样实现起来非常简便,但是就会有一个问题:如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降低系统的效率,因为频繁创建线程和销毁线程需要时间。   那么有没有一种办法使得线程可以复用,就是执行完一个任务,并不被销毁,而是可以继续执行其他的任务呢?   线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启

qq_43899283的博客 6988

【Cmder】--- Windows11 配置CMD神器 (超详细 持续更新中)

在编程的艺术世界里,代码和灵感需要寻找到最佳的交融点,才能打造出令人为之惊叹的作品。而在这座秋知叶i博客的殿堂里,我们将共同追寻这种完美结合,为未来的世界留下属于我们的独特印记。

秋知叶i 1万+

C语言线程池

线程池什么是线程池为什么要使用线程池线程池的工作流程图任务队列线程池的创建线程池的初始化工作者添加任务线程池的销毁完整代码threadpool.hpthreadpool.c总结 什么是线程池 线程池就是一个容纳多个线程的容器,对于一线线程我们可以多次对此线程进行重复使用,从而省去频繁创建线程对象的操作。 为什么要使用线程池 频繁的进行进程的创建与销毁将带来很多开销。不但如此,进程间频繁的切换也将减低 CPU 的利用率。 如果能复用之前创建的进程,而不是为每个并发任务创建一个进程,能有效降低进程创建与销毁的开

m0_61705102的博客 4470

封装POD与PinMap文件总结学习-20250516

芯片封装外形图(POD)和PinMap是芯片设计和制造中的关键文档。POD详细描述了芯片的物理尺寸、引脚布局和封装类型,而PinMap则提供了芯片封装上各个引脚的位置、名称和功能的详细信息。这些文档在芯片设计、制造和应用过程中起到“地图”的作用,帮助设计人员理解芯片的物理和电气特性。在PCB设计中,POD用于确定socket的footprint和pogo的选型,而PinMap则用于器件的合理布局和布线。这些信息对于确保芯片的正确安装和功能至关重要。

歌颂苦难的行为是无耻的; 2381

基于Simulink的超级电容与锂电池混合储能协调控制仿真

摘要:本文介绍基于Simulink的光伏-混合储能系统(HESS)建模与仿真方法,通过超级电容和锂电池的协同控制实现功率平抑。系统采用直流耦合架构,利用一阶低通滤波法将总功率分解为低频(锂电池承担)和高频分量(超级电容承担),并设计SOC自平衡机制维持超级电容工作点。仿真结果表明,该方案可使锂电池电流波动降低62%,光伏功率波动率降至7.5%,有效延长电池寿命。文章详细展示了从主电路搭建、功率分配到闭环控制的完整实现步骤,为新能源系统储能优化提供实用参考。

amy_mhd的博客 136

线程池原理及创建

线程池原理及创建本文给出了一个通用的线程池框架,该框架将与线程执行相关的任务进行了高层次的抽象,使之与具体的执行任务无关。另外该线程池具有动态伸缩性,它能根据执行任务的轻重自动调整线程池中线程的数量。文章的最后,我们给出一个简单示例程序,通过该示例程序,我们会发现,通过该线程池框架执行多线程任务是多么的简单。为什么需要线程池目前的大多数网络服务器,包括Web服务器、Email服务器以及数据库服务器

1268

Python实现PDB文件预处理

蛋白质结构研究依赖PDB文件存储的三维结构数据,但原始文件常含无关的水分子、离子和非标准残基等干扰信息。本文介绍了一个基于BioPython的Python预处理脚本,可自动清理PDB文件,主要功能包括:1)移除短于阈值的蛋白质链;2)过滤非标准氨基酸;3)可选保留水分子和金属离子。该脚本逻辑清晰,支持批量处理,能显著提升结构比对、分子对接等分析前的数据准备效率,为后续生物信息学研究提供更纯净的结构数据基础。

Protein Designer的博客 570
上一篇: hadoop 2.2.0 关于 fsimage & edit log 的相关配置
下一篇: 简单介绍VC++6.0下如何使用压缩库ZLIB
迷途小码
博客等级 码龄19年 71粉丝 95原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值