基于C++11/14的线程池(可添加任意类型函数任务)

基于cpp14完成的线程池,具体代码也可参考本人github工程。https://github.com/qin11152

原理

线程池对象中存在一个队列(deque)去存储业务层传递来的耗时任务,供线程池中的线程获取任务并执行。

线程池中根据设定的数量构造出指定数量的线程,这些线程会获取队列中的任务并执行,当任务队列为空时,则会挂起,等待队列不为空时条件变量通知唤醒。

以下列出具体实现,并进一步解释。

ThreadPool.h文件

#pragma once
#include <deque>
#include <memory>
#include <mutex>
#include <functional>
#include <condition_variable>
#include <vector>
#include <atomic>
#include <thread>

using Task = std::function<void()>;

class ThreadPool
{
public:
    //构造函数,默认开启10个线程
    ThreadPool(int num=10);
    ~ThreadPool();
    //开启此线程池
    void stopPool();
    //关闭线程池
    void startPool();
    //像任务队列中增加任务
    void addTask(Task task);
    //线程执行任务的函数
    void doTask();

private:
    std::condition_variable m_conDequeNotEmpty; //任务队列非空通知
    std::deque<Task> m_deqTask;     //任务队列
    std::mutex m_mutex;     //锁
    std::vector<std::thread> m_vecThread;   //线程存储在vec中
    int m_ithreadNum;   //线程数量
    std::atomic<bool> m_bIsRunning{ false };    //是否正在运行
};

ThreadPool.cpp

其中较为关键的两个成员函数为startPool和doTask。

startPool函数会根据设定的线程数量开启线程,使用c++11中的线程类创建线程,线程所执行的函数则为doTask。

在doTask函数中开启了while循环,首先要获得锁,保证获取deque中的值正确。获得锁之后则不断的查看队列的状态,当队列为空时条件变量就会进入等待状态,等待至队列不为空的通知或停止运行时,结束等待。之后便从任务队列中获取一个Task(Task为要执行的任务即function<void()>)并执行。

//开启线程池,创建一定数量的线程,并绑定dotask函数
void ThreadPool::startPool()
{
    m_bIsRunning = true;
    for (int i = 0; i < m_ithreadNum; ++i)
    {
        std::thread t(&ThreadPool::doTask, this);
        m_vecThread.push_back(move(t));
    }
}

void ThreadPool::doTask()
{
    //循环操作
    while (1)
    {
        //要获取的任务
        Task task;
        {
            std::unique_lock<std::mutex> lck(m_mutex);
            //正在运行状态且deque大小为空
            /*if (m_bIsRunning && 0 == m_deqTask.size())
            {
                printf("thread id:%d,", GetCurrentThreadId());
                printf("wiat state\n");
                //没有任务的时候就等待
                m_conDequeNotEmpty.wait(lck);
            }*/
            //等待任务队列不空或者状态为退出
            m_conDequeNotEmpty.wait(lck,[this]() {return !m_bIsRunning || !m_deqTask.empty(); });
            //不在运行状态且任务队列空了那就退出
            if (!m_bIsRunning&&m_deqTask.empty())
            {
                return;
            }
            //有任务就把顶端的拿出来
            task = move(m_deqTask.front());
            m_deqTask.pop_front();
        }
        //出了上边的作用域,lck就自动解锁了
        //执行任务
        task();
    }
}

#include "stdafx.h"
#include "ThreadPool.h"
#include <iostream>
#include <windows.h>


ThreadPool::ThreadPool(int num)
    :m_ithreadNum(num)
{
}

//析构时运行状态置为false,并通知所有等待线程,状态置为false后
//dotask中就可以退出
ThreadPool::~ThreadPool()
{
    m_bIsRunning = false;
    //通知所有线程不要再等待了
    m_conDequeNotEmpty.notify_all();
    for (auto &item : m_vecThread)
    {
        //回收线程资源
        if (item.joinable())
        {
            item.join();
        }
    }
}

void ThreadPool::stopPool()
{
    //运行状态置为false
    m_bIsRunning = false;
    //逻辑和析构函数一样
    m_conDequeNotEmpty.notify_all();
    for (auto &item : m_vecThread)
    {
        //回收线程资源
        if (item.joinable())
        {
            item.join();
        }
    }
}

//像任务队列中添加任务
void ThreadPool::addTask(Task task)
{
    if (m_bIsRunning)
    {
        //上锁,添加
        std::unique_lock<std::mutex> lck(m_mutex);
        m_deqTask.push_back(task);
        //通知任务队列不空
        m_conDequeNotEmpty.notify_one();
    }
}

main.cpp

#include <windows.h>

void func() {
    printf("task is doing,id:%d\n",GetCurrentThreadId());
    ::Sleep(6000);    //模拟工作时长
    printf("task finished,id:%d\n", GetCurrentThreadId());
}

int main()
{
    ThreadPool p(10);
    p.startPool();
    int num = 30;
    while (num--) {
        Sleep(500);
        p.addTask(func);
    }
    return 0;
}

添加任意类型任务

上述线程池包含线程池基本功能,但在其addtask时只能添加void()类型的函数,下面对其进行改进,使用模板元编程方法,使得线程池可接受任意类型的函数。

template<typename F, typename...Args>
auto addTask(F&& f, Args&&... args)
{
    std::function<decltype(f(args...))()> func = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
    auto task_ptr = std::make_shared<std::packaged_task<decltype(f(args...))()>>(func);
    std::function<void()> wrapperFunc = [=]() {
    (*task_ptr)();
    };
            
    m_deqTask.push_back(wrapperFunc);
    m_conDequeNotEmpty.notify_one();
    return task_ptr->get_future();
}

其中typename...Args为可变参数,可以接受任意数量的参数,通过bind函数将传入的函数f和对应的参数列表绑定为可执行对象,并通过packged_task封装为智能指针,最后通过匿名表达式包装为function<void()>类型,传入队列之中。如果先要获取执行结果,可以返回get_future,外部通过get获取结果,不然可以不返回值。

如果不使用packged_task再次封装一层,直接使用一下形式代码则会出现执行时对象已经释放的情况,造成崩溃。而function对象又无法封装为智能指针,故需使用packged_task。

    std::function<decltype(f(args...))()> func = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
    std::function<void()> wrapperFunc = [=]() {
        func();
    };

该类型线程池使用方法如下,给出了普通函数,类成员函数以及返回值的使用方法。

void func() 
{
    printf("task is doing,thread id:%d\n", GetCurrentThreadId());
    ::Sleep(6000);    //模拟工作时长
    printf("task finished,thread id:%d\n", GetCurrentThreadId());
}

int add(int a, int b)
{
    Sleep(2000);
    return a + b;
}

class TestPool
{
public:
    void func1(int a, int b)
    {
        printf("task is doing,thread id:%d\n", GetCurrentThreadId());
        int tmpNum = a + b;
        ::Sleep(6000);    //模拟工作时长
        printf("task finished,thread id:%d,result:%d\n", GetCurrentThreadId(), tmpNum);
    }
};

int main()
{
    ThreadPool threadPool(10);
    threadPool.startPool();
    auto result = threadPool.addTask(add, 1, 4);//获取返回结果
    threadPool.addTask(func);//普通函数
    printf("add result:%d\n", result.get());//get会阻塞程序执行
    TestPool testPool;
    threadPool.addTask(std::bind(&TestPool::func1, &testPool, std::placeholders::_1, std::placeholders::_2), 3, 4);//成员函数
    return 0;
}

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是一个基于C 11的线程池代码,包含线程池的创建、销毁、任务添加任务执行等基本功能: ``` #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <stdbool.h> // 定义任务结构体 typedef struct task { void *(*func)(void *); // 任务函数 void *arg; // 任务参数 struct task *next; // 下一个任务 } task_t; // 定义线程池结构体 typedef struct thread_pool { pthread_mutex_t lock; // 互斥锁 pthread_cond_t notify; // 条件变量 pthread_t *threads; // 线程数组 task_t *queue; // 任务队列 bool is_shutdown; // 线程池是否关闭标志 int thread_count; // 线程数 int queue_size; // 任务队列长度 } thread_pool_t; // 初始化线程池 void thread_pool_init(thread_pool_t *pool, int thread_count, int queue_size) { pthread_mutex_init(&(pool->lock), NULL); pthread_cond_init(&(pool->notify), NULL); pool->threads = (pthread_t *)malloc(sizeof(pthread_t) * thread_count); pool->queue = NULL; pool->is_shutdown = false; pool->thread_count = thread_count; pool->queue_size = queue_size; // 创建指定数量的线程 for (int i = 0; i < thread_count; i++) { pthread_create(&(pool->threads[i]), NULL, thread_pool_worker, (void *)pool); } } // 线程池工作函数 void *thread_pool_worker(void *arg) { thread_pool_t *pool = (thread_pool_t *)arg; while (true) { pthread_mutex_lock(&(pool->lock)); while (pool->queue == NULL && !pool->is_shutdown) { pthread_cond_wait(&(pool->notify), &(pool->lock)); } if (pool->is_shutdown) { pthread_mutex_unlock(&(pool->lock)); pthread_exit(NULL); } // 取出任务并执行 task_t *task = pool->queue; pool->queue = pool->queue->next; pthread_mutex_unlock(&(pool->lock)); (*(task->func))(task->arg); free(task); } } // 添加任务线程池 void thread_pool_add_task(thread_pool_t *pool, void *(*func)(void *), void *arg) { task_t *task = (task_t *)malloc(sizeof(task_t)); task->func = func; task->arg = arg; task->next = NULL; pthread_mutex_lock(&(pool->lock)); if (pool->queue == NULL) { pool->queue = task; } else { task_t *temp = pool->queue; while (temp->next != NULL) { temp = temp->next; } temp->next = task; } pthread_cond_signal(&(pool->notify)); pthread_mutex_unlock(&(pool->lock)); } // 销毁线程池 void thread_pool_destroy(thread_pool_t *pool) { pool->is_shutdown = true; // 唤醒所有线程并等待它们退出 pthread_cond_broadcast(&(pool->notify)); for (int i = 0; i < pool->thread_count; i++) { pthread_join(pool->threads[i], NULL); } // 销毁任务队列 task_t *task; while (pool->queue != NULL) { task = pool->queue; pool->queue = task->next; free(task); } // 销毁互斥锁和条件变量 pthread_mutex_destroy(&(pool->lock)); pthread_cond_destroy(&(pool->notify)); free(pool->threads); } ``` 使用方法: 1. 首先定义一个 `thread_pool_t` 结构体变量; 2. 调用 `thread_pool_init` 函数初始化线程池,传入线程数和任务队列长度; 3. 调用 `thread_pool_add_task` 函数添加任务,传入任务函数和参数; 4. 线程池会自动执行添加任务; 5. 最后调用 `thread_pool_destroy` 函数销毁线程池。 例如,下面的代码创建一个线程池添加3个任务,然后销毁线程池: ``` void *task_func(void *arg) { int num = *((int *)arg); printf("Task %d is running.\n", num); usleep(100000); return NULL; } int main() { thread_pool_t pool; thread_pool_init(&pool, 2, 5); int args[3] = {1, 2, 3}; for (int i = 0; i < 3; i++) { thread_pool_add_task(&pool, task_func, (void *)&args[i]); } sleep(1); thread_pool_destroy(&pool); return 0; } ``` 输出结果为: ``` Task 1 is running. Task 2 is running. Task 3 is running. ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值