首页 > 编程语言 >C++ 线程池

C++ 线程池

时间:2024-09-22 14:34:11浏览次数:1  
标签:std task lock C++ running done 线程 include

#include <iostream>
#include <string>
#include <memory>
#include <vector>
#include <thread>
#include <queue>
#include <functional>
#include <mutex>
using namespace std;

class ThreadPool
{
public:
    ThreadPool(int numThreads) :m_Stop(false)
    {
        for (int i = 0; i != numThreads; ++i)
        {
            m_Threads.emplace_back([this]
                {
                    while (true)
                    {
                        std::unique_lock<std::mutex> lock(m_Mutex);
                        m_Condition.wait(lock, [this] { return !m_Tasks.empty() || m_Stop; });
                        if (m_Stop && m_Tasks.empty()) return;

                        std::function<void()> task(std::move(m_Tasks.front()));
                        m_Tasks.pop();
                        lock.unlock();
                        task();
                    }
                });
        }
    }
    ~ThreadPool()
    {
        {
            std::unique_lock<std::mutex> lock(m_Mutex);
            m_Stop = true;
        }
        m_Condition.notify_all();
        for (auto &t : m_Threads)
        {
            t.join();
        }
    }
    ThreadPool(ThreadPool &) = delete;
    ThreadPool &operator=(const ThreadPool &) = delete;
    template<class F, class... Args>
    void enQueue(F &&f, Args&&... args)
    {
        std::function<void()> task =
            std::bind(std::forward<F>(f), std::forward<Args>(args)...);
        {
            std::unique_lock<std::mutex> lock(m_Mutex);
            m_Tasks.emplace(std::move(task));
        }
        m_Condition.notify_all();
    }
private:
    std::vector<std::thread> m_Threads;
    std::queue<std::function<void()>> m_Tasks;
    std::mutex m_Mutex;
    std::condition_variable m_Condition;
    bool m_Stop;
};

int main()
{
    ThreadPool th_pool(4);
    for (int i = 0; i != 10; ++i)
    {
        th_pool.enQueue([i]
            {
                std::cout << "task : " << i << " is running " << '\n';
                std::this_thread::sleep_for(std::chrono::seconds(1));
                std::cout << "task : " << i << " is done " << '\n';
            });
    }

    system("pause");
    return EXIT_SUCCESS;
}

输出:

task : 0 is running
task : 1 is running
task : 2 is running
task : 3 is running
请按任意键继续. . . task : 0 is done
task : 4 is running
task : 2 is done
task : 5 is running
task : 1 is done
task : 6 is running
task : 3 is done
task : 7 is running
task : 4 is done
task : task : 85 is done
 is running
task : 6task : 9 is running  is done

task : 7 is done
task : 8 is done
task : 9 is done




参考:https://www.bilibili.com/video/BV1d841117SH?p=9&vd_source=d63f54e500587f56976cc02586e53496

标签:std,task,lock,C++,running,done,线程,include
From: https://www.cnblogs.com/huvjie/p/18425257

相关文章

  • C++:数组与字符串
    一、数组         数组是一种存储若干元素的数据类型,在诸多编程语言中存在,其显著的特点是元素通常是在物理层面上连续存储的(逻辑上的数组,比如链表,可能不是),并且具有极快的元素访问速度。    数组通常是同构的(homogenous ),即数组中的元素都是同一类型的,......
  • [数据结构与算法·C++] 笔记 1.4 算法复杂性分析
    1.4算法复杂性分析算法的渐进分析数据规模n逐步增大时,f(n)的增长趋势当n增大到一定值以后,计算公式中影响最大的就是n的幂次最高的项其他的常数项和低幂次项都可以忽略大O表示法函数f,g定义域为自然数,值域非负实数集定义:如果存在正数c和n,使得对任意的......
  • C++ 异步 async future 等
    async和future这个和C#的Task有点像。#include<iostream>#include<string>#include<memory>#include<future>#include<thread>usingnamespacestd;intcalculate(){std::this_thread::sleep_for(std::chrono::seconds(2));......
  • C++ std::call_once 实现单例模式
    #if1#include<iostream>#include<memory>#include<mutex>usingnamespacestd;classSingleton{public:staticSingleton&getInstance(){std::call_once(m_OnceFlag,&Singleton::init);return*m_Insta......
  • 【C/C++】速通涉及string类的经典编程题
    【C/C++】速通涉及string类的经典编程题一.字符串最后一个单词的长度代码实现:(含注释)二.验证回文串解法一:代码实现:(含注释)解法二:(推荐)1.函数isalnum介绍:2.函数tolower介绍:3.代码实现:三.翻转字符串II:区间部分翻转代码实现:(含注释)四.翻转字符串III:翻转字符串中的单词代......
  • 【多线程面试题】涵盖三个常见的场景
    1.多线程轮流打印数字最简单的代码题,使用两种加锁方式,sychronized和ReentranLocksychronizedpublicclassMain{privatestaticfinalObjectlock=newObject();privatestaticintnum=100;privatestaticintcnt=0;publicstaticvoidm......
  • 解锁Java线程池:实战技巧与陷阱规避
    专业在线打字练习网站-巧手打字通,只输出有价值的知识。一前言线程池作为初学者常感困惑的一个领域,本次“巧手打字通课堂”将深入剖析其中几个最为普遍的误区。为了更清晰地阐述这些知识点,让我们以一个具体定义的线程池为例来展开说明。如下:ThreadPoolExecutorexecutor=ne......
  • 01背包问题之背包容量为什么要倒序遍历?(以C++代码具体实现为例)
    首先是先阐述一下背包问题:有n件物品和一个最多能背重量为w的背包。第i件物品的重量是weight[i],得到的价值是value[i]。每件物品只能用依次,求解将哪些物品装入背包里物品价值总和最大。这里不解释代码的其他部分,只对代码中的背包容量遍历进行具体的解释,首先给出遍历部分的代......
  • C++ 笔试常用算法模板
    C++笔试常用算法模板一、二叉树遍历DFSBFS二、回溯模板三、动态规划01背包朴素版本滚动数组优化完全背包朴素版本滚动数组优化最长递增子序列朴素版本贪心+二分优化最长公共子序列最长回文子串四、图建图邻接矩阵邻接表图的遍历DFSBFS拓扑排序并查集最小生成树Kr......
  • C++: 使用红黑树模拟实现STL中的map和set
    目录1.红黑树的迭代器++和--2.改造红黑树3.set的模拟实现4.map的模拟实现5.RBTree的改造代码博客主页:酷酷学正文开始1.红黑树的迭代器迭代器的好处是可以方便遍历,是数据结构的底层实现与用户透明打开C++的源码我们可以发现,其实源码中的底层大概如下......