栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++多线程——简单线程池

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++多线程——简单线程池

安全队列

#include 
#include 
#include 
#include 
#include 
#include "tsafe_queue.h"
using namespace std;
class join_t {
    vector& threads;
public:
    explicit join_t(vector& ts):threads(ts)
    {}
    ~join_t() {
        for (int i = 0; i < threads.size(); i++) {
            if (threads[i].joinable())
                threads[i].join();
        }
    }
};
class t_pool {
    atomic_bool done;
    tsafe_queue> works; //工作队列
    vector threads;//线程池
    join_t joiner;//初始化类
    void worker_thread() {
        while (!done) {
            function task;
            if (works.try_pop(task)) {
                task();
            }
            else {
                this_thread::yield();//没有任务时,让出时间片
            }
        }
    }
public:
    t_pool() :done(false), joiner(threads) {
        unsigned const max_t = thread::hardware_concurrency() - 2;
        try {//创建同样数量的线程
            for (unsigned i = 0; i < max_t; i++) {
                threads.push_back(
                    std::thread(&t_pool::worker_thread, this));
            }
        }
        catch (...) {
            done = true;
            throw;
        }
    }
    ~t_pool() {
        done = false;
    }
    template
    void submit(F_T f) {
        works.push(function(f));
    }
};

启动线程池以后,每个线程都在等待分配任务,都会去等待队列中取出任务。
简单测试一下。

int main()
{
    t_pool p;
    for (int i = 0; i < 1000; i++) {
        p.submit([i]() {
            cout << i * i<
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/289999.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号