基于c++11的100行实现简单线程池

基于c++11的100行实现简单线程池

原文:https://blog.csdn.net/gcola007/article/details/78750220
原项目地址:https://github.com/progschj/ThreadPool/blob/master/ThreadPool.h

背景

刚粗略看完一遍c++ primer第五版,一直在找一些c++小项目练手,实验楼里面有很多项目,但是会员太贵了,学生党就只能google+github自行搜索完成项目了。注:本文纯提供自己的理解,代码完全照抄,有想法的欢迎评论留言一起讨论。

本文参考:

c++11线程池实现
A simple C++11 Thread Pool implementation

涉及到的c++11的特性:

std::vector
std::thread
std::mutex
std::future
std::condition_variable

线程池原理介绍

线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。线程池线程都是后台线程。每个线程都使用默认的堆栈大小,以默认的优先级运行,并处于多线程单元中。

线程池的组成部分:

线程池管理器(ThreadPoolManager):用于创建并管理线程池
工作线程(WorkThread): 线程池中线程
任务接口(Task):每个任务必须实现的接口,以供工作线程调度任务的执行。
任务队列:用于存放没有处理的任务。提供一种缓冲机制。

1、代码:ThreadPool.h

#ifndef THREAD_POOL_H
#define THREAD_POOL_H

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

class ThreadPool {
public:
    ThreadPool(size_t);
    template<class F, class... Args>
    auto enqueue(F&& f, Args&&... args) 
        -> std::future<typename std::result_of<F(Args...)>::type>;
    ~ThreadPool();
private:
    // need to keep track of threads so we can join them
    std::vector< std::thread > workers;
    // the task queue
    std::queue< std::function<void()> > tasks;

    // synchronization
    std::mutex queue_mutex;
    std::condition_variable condition;
    bool stop;
};

// the constructor just launches some amount of workers
inline ThreadPool::ThreadPool(size_t threads)
    :   stop(false)
{
    for(size_t i = 0;i<threads;++i)
        workers.emplace_back(
            [this]
            {
                for(;;)
                {
                    std::function<void()> task;

                    {
                        std::unique_lock<std::mutex> lock(this->queue_mutex);
                        this->condition.wait(lock,
                            [this]{ return this->stop || !this->tasks.empty(); });
                        if(this->stop && this->tasks.empty())
                            return;
                        task = std::move(this->tasks.front());
                        this->tasks.pop();
                    }

                    task();
                }
            }
        );
}

// add new work item to the pool
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args) 
    -> std::future<typename std::result_of<F(Args...)>::type>
{
    using return_type = typename std::result_of<F(Args...)>::type;

    auto task = std::make_shared< std::packaged_task<return_type()> >(
            std::bind(std::forward<F>(f), std::forward<Args>(args)...)
        );

    std::future<return_type> res = task->get_future();
    {
        std::unique_lock<std::mutex> lock(queue_mutex);

        // don't allow enqueueing after stopping the pool
        if(stop)
            throw std::runtime_error("enqueue on stopped ThreadPool");

        tasks.emplace([task](){ (*task)(); });
    }
    condition.notify_one();
    return res;
}

// the destructor joins all threads
inline ThreadPool::~ThreadPool()
{
    {
        std::unique_lock<std::mutex> lock(queue_mutex);
        stop = true;
    }
    condition.notify_all();
    for(std::thread &worker: workers)
        worker.join();
}

#endif

线程池大约100行,下面是运行代码

2、代码:example.cpp

#include <iostream>
#include <vector>
#include <chrono>

#include "ThreadPool.h"

int main()
{

    ThreadPool pool(4);
    std::vector< std::future<int> > results;

    for(int i = 0; i < 8; ++i) {
        results.emplace_back(
            pool.enqueue([i] {
                std::cout << "hello " << i << std::endl;
                std::this_thread::sleep_for(std::chrono::seconds(1));
                std::cout << "world " << i << std::endl;
                return i*i;
            })
        );
    }

    for(auto && result: results)
        std::cout << result.get() << ' ';
    std::cout << std::endl;

    return 0;
}

代码剖析

通过新建一个线程池类,以类来管理资源(《c++ effective》资源管理一章有提到)。该类包含3个公有成员函数与5个私有成员:构造函数与析构函数即满足(RAII:Resource Acquisition Is Initialization)。

:
构造函数接受一个size_t类型的数,表示连接数
enqueue表示线程池部分中的任务管道,是一个模板函数
workers是一个成员为thread的vector,用来监视线程状态
tasks表示线程池部分中的任务队列,提供缓冲机制
queue_mutex表示互斥锁
condition表示条件变量(互斥锁,条件变量以及stop将在后面通过例子说明)

queue_mutex、condition与stop这三个成员让初次接触多线程的我非常的迷惑,互斥到底是什么意思?为什么需要一个bool量来控制?条件变量condition又是什么?
不懂的可以搜索:多线程的生产者与消费者模型
同时附上condition_variable详解

  • 构造函数ThreadPOOL(size_t):
    省略了参数
    emplace_back相当于push_back但比push_back更为高效
    wokers压入了一个lambda表达式(即一个匿名函数),表示一个任务(线程),使用for的无限循环,task表示函数对象,线程池中的函数接口在enqueue传入的参数之中,condition.wait(lock,bool),当bool为false的时候,线程将会被堵塞挂起,被堵塞时需要notify_one来唤醒线程才能继续执行

  • 任务队列函数enqueue(F&& f, Args&&… args)
    这类多参数模板的格式就是如此
    -> 尾置限定符,语法就是如此,用来推断auto类型
    typename与class的区别
    result_of用来得到返回类型的对象,它有一个成员::type

  • 析构函数~ThreadPool()
    通过notify_all可以唤醒线程竞争任务的执行,从而使所有任务不被遗漏

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值