简单的thread_pool代码

本文介绍了一个简单的线程池实现方法,包括初始化、任务添加和销毁等关键步骤,并通过一个示例展示了如何使用该线程池来并发处理任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>

#define DEFAULT_THREAD_NUM 4

typedef struct job_s {
    void *(*process)(void*);
    void *arg;
    struct job_s *next;
}job_t;

typedef struct thread_pool_s {
    pthread_mutex_t queue_lock;
    pthread_cond_t  queue_ready;
    job_t           *queue_head;
    unsigned int    cur_queue_size;
    pthread_t       *tids;
    unsigned int    max_thread_num;
    int             shutdown;
}thread_pool_t;

thread_pool_t *pool = NULL;

void *thread_routine(void *arg) {
    printf("thread 0x%x is starting.\n", (unsigned int)pthread_self());
    while (1) {
        pthread_mutex_lock(&(pool->queue_lock));
        while (0 == pool->cur_queue_size && 0 == pool->shutdown) {
            printf("thread 0x%x is waiting.\n", (unsigned int)pthread_self());
            pthread_cond_wait(&(pool->queue_ready), &(pool->queue_lock));
        }
        if (pool->shutdown) {
            pthread_mutex_unlock(&(pool->queue_lock));
            printf("thread 0x%x will exit.\n", (unsigned int)pthread_self());
            pthread_exit(NULL);
        }
        job_t *temp = pool->queue_head;
        pool->queue_head = temp->next;
        pool->cur_queue_size--;
        pthread_mutex_unlock(&(pool->queue_lock));
        (*temp->process)(temp->arg);
        free(temp);
    }
    return NULL;
}

int thread_pool_init(int max_thread_num) {// initialize by the order defined
    int i;
    if (max_thread_num <= 0)
        max_thread_num = DEFAULT_THREAD_NUM;
    pool = (thread_pool_t*)malloc(sizeof(thread_pool_t));
    if (NULL == pool)
        return -1;
    pthread_mutex_init(&(pool->queue_lock), NULL);
    pthread_cond_init(&(pool->queue_ready), NULL);
    pool->queue_head = NULL;
    pool->cur_queue_size = 0;
    pool->tids = (pthread_t*)malloc(max_thread_num * sizeof(pthread_t));
    if (NULL == pool->tids) {
        free(pool);
        pool = NULL;
        return -1;
    }
    for (i = 0; i < max_thread_num; i++) {
        printf("thread 0x%x is creating.\n", (unsigned int)pthread_self());
        pthread_create(&(pool->tids[i]), NULL, (void*)thread_routine, NULL);
    }
    pool->shutdown = 0;
    return 1;
}

int thread_pool_add(void *(*process)(void*), void *arg) {
    job_t *temp = (job_t*)malloc(sizeof(job_t));
    temp->process = process;
    temp->arg = arg;
    temp->next = NULL;
    pthread_mutex_lock(&(pool->queue_lock));
    if (NULL == pool->queue_head) {
        pool->queue_head = temp;
    } else {
        job_t *p = pool->queue_head;
        while (p->next) 
            p = p->next;
        p->next = temp;
    }
    pool->cur_queue_size++;
    pthread_cond_signal(&(pool->queue_ready));
    pthread_mutex_unlock(&(pool->queue_lock));
    return 0;
}

int thread_pool_destroy() {// 0 means success and -1 means failed.
    int i;
    if (pool->shutdown)
        return -1;
    pthread_cond_broadcast(&(pool->queue_ready));
    for (i = 0; i < pool->max_thread_num; i++)
        pthread_join(pool->tids[i], NULL);
    free(pool->tids);
    job_t *p = pool->queue_head;
    while (p) {
        pool->queue_head = p->next;
        free(p);
        p = pool->queue_head;
    }
    pool->shutdown = 1;
    //pthread_mutex_destory(&(pool->queue_lock));
    //pthread_cond_destory(&(pool->queue_ready));
    free(pool);
    pool = NULL;
    return 0;
}

void *my_process(void *arg) {
    printf("thread 0x%x is working on task %d.\n", (unsigned int)pthread_self(), *(int*)arg);
    sleep(1);
    return NULL;
}

int main(int argc, char *argv[]) {
    int i;
    thread_pool_init(3);
    int *datas = (int*)malloc(sizeof(int) * 10);
    for (i = 0; i < 10; i++) {
        datas[i] = i;
        thread_pool_add(my_process, (datas + i));
    }
    sleep(5);
    thread_pool_destroy();
    free(datas);
    return 0;
}

<think>好的,用户让我介绍一下basic_thread_pool的submit功能,用中文回答。首先,我需要确认用户对线程池的基本概念是否了解,可能需要先简单解释线程池的作用。不过用户可能已经有一定基础,直接询问submit的话,可能更关注具体用法和实现细节。 接下来,我得考虑用户的使用场景。可能是在进行多线程编程时遇到了问题,或者想优化现有代码的性能。用户可能是一个开发者,正在尝试使用线程池来管理任务提交,但不太清楚submit方法的具体工作机制。 然后,我需要明确basic_thread_pool的定义。由于C++标准库中没有直接提供这个类,它可能是第三方库或自定义实现的线程池。不同实现的submit方法可能有所不同,但通常核心功能是提交任务到线程池中执行,并可能返回future对象来获取结果。 需要解释submit的基本功能,即异步执行任务,并可能支持获取返回值。同时,要说明参数传递的方式,比如函数、lambda表达式、可调用对象等,以及如何传递参数给任务函数。 还要提到submit的返回值,比如std::future,这样用户知道如何获取异步操作的结果或异常。可能还需要给出一个简单代码示例,帮助用户直观理解使用方法。 另外,异常处理也是需要注意的地方,需要说明在线程池任务中抛出的异常会如何传播到future中,这样用户在调试时能知道如何处理异常情况。 最后,总结submit方法的作用和优势,比如简化线程管理、提高性能、方便结果获取等,确保用户全面了解其用途。</think>`basic_thread_pool` 通常指一种基础的线程池实现(常见于 C++ 或其他语言的多线程编程中),其 `submit` 方法是用于向线程池提交异步任务的核心接口。以下是详细介绍: --- ### **功能说明** `submit` 方法的作用是 **将任务(函数、Lambda、可调用对象)提交到线程池的任务队列中**,由线程池中的空闲线程自动执行。任务会被异步处理,提交后立即返回,不会阻塞当前线程。 --- ### **核心特点** 1. **异步执行** 任务不会立即执行,而是排队等待线程池中的线程处理。适合处理耗时操作(如 I/O、计算等)。 2. **参数传递** 支持向任务传递任意参数(值传递或引用传递,需注意生命周期)。 3. **返回值处理** 通常返回一个 `std::future` 对象,可通过它获取任务的返回值或捕获异常(若任务有返回值)。 --- ### **代码示例(C++ 伪代码)** ```cpp #include <thread_pool> // 假设线程池库 int compute_sum(int a, int b) { return a + b; } int main() { basic_thread_pool pool(4); // 创建4个线程的线程池 // 提交任务并获取 future auto future = pool.submit(compute_sum, 2, 3); // 等待结果(可选) int result = future.get(); std::cout << "Result: " << result; // 输出 5 return 0; } ``` --- ### **参数与返回值** - **输入参数** - 第一个参数为可调用对象(函数、Lambda、函数对象)。 - 后续参数为传递给任务的参数(按值或引用传递)。 - **返回值** - 返回 `std::future<T>`,其中 `T` 是任务返回值的类型。若任务无返回值,则为 `std::future<void>`。 --- ### **异常处理** 如果任务中抛出异常,异常会被捕获并存储到 `std::future` 中。调用 `future.get()` 时会重新抛出该异常,需使用 `try-catch` 处理。 --- ### **典型应用场景** - 并行计算(如分块处理数据) - 异步 I/O 操作(如文件读写、网络请求) - 事件驱动编程(如 GUI 后台任务)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值