前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >一个只有100行代码的线程池开源项目

一个只有100行代码的线程池开源项目

作者头像
CPP开发前沿
发布2024-07-04 16:07:21
130
发布2024-07-04 16:07:21
举报
文章被收录于专栏:CPP开发前沿CPP开发前沿

项目使用C++ 11编写,只有一个头文件,但是在github上却获得了7600个stars和2200个fork。非常值得大家下载下来学习,尤其是想要学习多线程编码的同学。

代码相当简明,所有的代码都在 一个类中实现,对外暴露的也仅仅是一个构造函数、一个析构函数以及一个模板函数。具体如下:

代码语言:javascript
复制
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;
};

使用起来也相对简单.即使是刚入门也可以轻松使用,使用案例参考如下代码:

代码语言:javascript
复制
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;
}
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2024-07-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 CPP开发前沿 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档