基于c++11实现的简易线程池(任意参数任务)

前言

该线程池只是一个简单的线程池模型,只是为了将c++11的多线程编程技术进行应用实战,仅涉及到c++11的多线程编程技术和生产者消费者模型,任务队列和线程池的管理并没有实现

代码托管在JL-sky/threadPool: 基于c++分别实现手写future库与信号量构建线程池与使用future库和模版编程构建线程池

实现

threadPool.h

#ifndef THREADPOOL_H
#define THREADPOOL_H

#include <atomic>
#include <condition_variable>
#include <functional>
#include <future>
#include <memory>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>

class ThreadPool {
 public:
    ThreadPool(int size = std::thread::hardware_concurrency())
        : pool_size_(size), isStop_(false) {
        //线程池初始化
        for (int i = 0; i < pool_size_; ++i) {
            // threads_.push_back(std::thread(&ThreadPool::worker,this));
            threads_.emplace_back([this]() { worker(); });
        }
    }

    ~ThreadPool() { ShutDown(); }
    //线程池关闭函数,单独写成一个函数是为了让用户可以手动关闭
    void ShutDown() {
        //关闭线程池
        isStop_ = true;
        //通知所有线程,如果正在工作就将手头的任务处理掉
        not_empty_cond_.notify_all();
        //等待所有线程处理掉自己的任务
        for (auto &thread : threads_) {
            if (thread.joinable())
                thread.join();
        }
    }
    
    //任务提交函数 ---》生产者
    template <typename F, typename... Args>
    auto Submit(F &&f, Args &&...args) -> std::future<decltype(f(args...))> {
        //定义任务函数返回类型
        using func_type = decltype(f(args...));
        //将任务函数包装成一个异步任务,并使用shared_ptr进行管理
        auto task_ptr = std::make_shared<std::packaged_task<func_type()>>(
            std::bind(std::forward<F>(f), std::forward<Args>(args)...));
        std::future<func_type> func_future = task_ptr->get_future();
        //扮演生产者角色,向任务队列中添加任务
        {
            std::lock_guard<std::mutex> lock(mtx_);
            if (isStop_)
                throw std::runtime_error("threadpool has stop!!!");
            task_queue_.emplace([task_ptr]() { (*task_ptr)(); });
        }
        not_empty_cond_.notify_one();

        return func_future;
    }

 private:
    //线程池关闭标志
    std::atomic_bool isStop_;
    //线程池容量大小
    int pool_size_;
    
    //任务类型
    using Task = std::function<void()>;
    //线程池
    std::vector<std::thread> threads_;
    //任务队列
    std::queue<Task> task_queue_;
    //队列数据的互斥访问
    std::mutex mtx_;
    //任务队列非空信号
    std::condition_variable not_empty_cond_;
    //工作函数 ---》 消费者
    void worker() {
        while (1) {
            std::unique_lock<std::mutex> lock(mtx_);
            //等待任务提交函数向队列中添加任务
            not_empty_cond_.wait(
                lock, [this]() { return isStop_ || !task_queue_.empty(); });

            if (isStop_ && task_queue_.empty())
                return;
            //取出任务
            Task task = task_queue_.front();
            task_queue_.pop();
            //队列的互斥访问已经结束,可以提前结束锁,否则会一直等到任务执行结束后才自动释放锁,会降低程序并发性能
            lock.unlock();
            //执行任务
            task();
        }
        return;
    }
};

#endif // THREADPOOL_H

测试

加法测试

int add(const int &num1, const int &num2) { return num1 + num2; }
void addTest() {
    ThreadPool pool;
    auto task1 = pool.Submit(add, 1, 2);
    auto task2 = pool.Submit(add, 3, 4);
    int sum = task1.get() + task2.get();
    std::cout << "sum=" << sum << std::endl;
}

矩阵乘法测试

矩阵乘法的每一个元素计算可以看作是独立的任务,因为矩阵乘法的每个元素是通过两个矩阵的行和列对应元素的乘积之和来计算的。由于这些元素的计算是彼此独立的,因此我们可以使用线程池来并行计算矩阵的每一个元素。

任务设计

对于矩阵 A和 B,假设 A是一个 m×n 矩阵,B是一个 n×p矩阵,那么结果矩阵 C将是一个 m×p矩阵。矩阵乘法的每个元素 C[i][j]是由如下计算得到:

我们可以将每一个 C[i][j]的计算任务分配给一个线程,这样线程池就可以并行计算矩阵乘法的各个元素。


// 矩阵乘法
std::vector<std::vector<int>>
MatrixMultiply(const std::vector<std::vector<int>> &A,
               const std::vector<std::vector<int>> &B, ThreadPool &pool) {
    size_t m = A.size();    // A的行数
    size_t n = A[0].size(); // A的列数
    size_t p = B[0].size(); // B的列数

    std::vector<std::vector<int>> C(m, std::vector<int>(p, 0)); // 结果矩阵

    std::vector<std::future<void>> futures;

    // 为结果矩阵中的每个元素提交一个计算任务
    for (size_t i = 0; i < m; ++i) {
        for (size_t j = 0; j < p; ++j) {
            futures.push_back(pool.Submit([i, j, &A, &B, &C, n]() {
                int sum = 0;
                for (size_t k = 0; k < n; ++k) {
                    sum += A[i][k] * B[k][j];
                }
                C[i][j] = sum;
            }));
        }
    }

    // 等待所有的任务完成
    for (auto &future : futures) {
        future.get();
    }

    return C;
}

std::ostream &operator<<(std::ostream &os,
                         std::vector<std::vector<int>> &nums) {
    int col = 0;
    int m = nums.size();
    int n = nums[0].size();
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            os << nums[i][j] << " ";
            col++;
            if (col % n == 0)
                os << "\n";
        }
    }
    return os;
}

void multiTest() {
    // 定义两个矩阵 A 和 B
    std::vector<std::vector<int>> A = {{1, 2, 3}, {4, 5, 6}};
    std::vector<std::vector<int>> B = {{7, 8}, {9, 10}, {11, 12}};

    ThreadPool pool(A.size() * B[0].size());
    // 计算矩阵 A 和 B 的乘积
    std::vector<std::vector<int>> C =
        MatrixMultiply(A, B, pool); // 使用 *pool_ 来解引用智能指针

    // std::vector<std::vector<int>> expected = {{58, 64}, {139, 154}};
    std::cout << C;
}

完整测试

#include "threadPool.h"
#include <iostream>

int add(const int &num1, const int &num2) { return num1 + num2; }
void addTest() {
    ThreadPool pool;
    auto task1 = pool.Submit(add, 1, 2);
    auto task2 = pool.Submit(add, 3, 4);
    int sum = task1.get() + task2.get();
    std::cout << "sum=" << sum << std::endl;
}

// 矩阵乘法
std::vector<std::vector<int>>
MatrixMultiply(const std::vector<std::vector<int>> &A,
               const std::vector<std::vector<int>> &B, ThreadPool &pool) {
    size_t m = A.size();    // A的行数
    size_t n = A[0].size(); // A的列数
    size_t p = B[0].size(); // B的列数

    std::vector<std::vector<int>> C(m, std::vector<int>(p, 0)); // 结果矩阵

    std::vector<std::future<void>> futures;

    // 为结果矩阵中的每个元素提交一个计算任务
    for (size_t i = 0; i < m; ++i) {
        for (size_t j = 0; j < p; ++j) {
            futures.push_back(pool.Submit([i, j, &A, &B, &C, n]() {
                int sum = 0;
                for (size_t k = 0; k < n; ++k) {
                    sum += A[i][k] * B[k][j];
                }
                C[i][j] = sum;
            }));
        }
    }

    // 等待所有的任务完成
    for (auto &future : futures) {
        future.get();
    }

    return C;
}

std::ostream &operator<<(std::ostream &os,
                         std::vector<std::vector<int>> &nums) {
    int col = 0;
    int m = nums.size();
    int n = nums[0].size();
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            os << nums[i][j] << " ";
            col++;
            if (col % n == 0)
                os << "\n";
        }
    }
    return os;
}

void multiTest() {
    // 定义两个矩阵 A 和 B
    std::vector<std::vector<int>> A = {{1, 2, 3}, {4, 5, 6}};
    std::vector<std::vector<int>> B = {{7, 8}, {9, 10}, {11, 12}};

    ThreadPool pool(A.size() * B[0].size());
    // 计算矩阵 A 和 B 的乘积
    std::vector<std::vector<int>> C =
        MatrixMultiply(A, B, pool); // 使用 *pool_ 来解引用智能指针

    // std::vector<std::vector<int>> expected = {{58, 64}, {139, 154}};
    std::cout << C;
}

int main() {
    addTest();
    multiTest();
    return 0;
}

参考

C++ 线程池 - 敬方的个人博客 | JF Blog

基于C++11实现线程池 - 知乎

恋恋风辰官方博客

基于C++11的线程池(threadpool),简洁且可以带任意多的参数 - _Ong - 博客园

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值