写一个简单的线程池

线程池代码(代码太少了就不分cpp/h了):

复制代码
 1 #include <condition_variable>
 2 #include <deque>
 3 #include <iostream>
 4 #include <mutex>
 5 #include <thread>
 6 
 7 class ThreadPool {
 8   using Task = std::function<void(void)>;
 9 
10  private:
11   bool stop_flag_;                     //线程停止标志值
12   const int thread_num_;               //线程数
13   std::mutex task_mutex_;              //任务数据锁
14   std::condition_variable task_cond_;  //任务数据的条件变量
15   std::deque<Task> task_queue_;  //任务队列(高优先级任务可以推到头部)
16   std::vector<std::thread> threads_;  //线程
17 
18  public:
19   explicit ThreadPool(int thread_num = 1)
20       : thread_num_(thread_num), stop_flag_(false) {
21     const int max_thread = std::thread::hardware_concurrency();
22     if (thread_num_ > max_thread) {  //限制线程数量
23       std::wclog << "max thread is " << max_thread << std::endl;
24       std::wclog << "thread trim to " << max_thread << std::endl;
25     }
26     for (int i = 0; i < std::min(thread_num_, max_thread); ++i) {
27       threads_.emplace_back(std::thread(std::bind(&ThreadPool::Execute, this)));
28     }
29   }
30 
31   //添加任务
32   void AddTask(Task task) {
33     std::unique_lock<std::mutex> lock(task_mutex_);
34     task_queue_.push_back(std::move(task));
35     task_cond_.notify_all();
36   }
37   //关闭线程池
38   void Halt() {
39     stop_flag_ = true;
40     std::unique_lock<std::mutex> lock(task_mutex_);
41     std::cout << task_queue_.size() << " tasks remain~~~~ " << std::endl;
42     std::cout << "halt.........." << std::endl;
43     task_queue_.clear();
44     task_queue_.push_back([]() { return; });
45     task_cond_.notify_all();
46     lock.unlock();
47     std::cout << threads_.size() << " threads remain " << std::endl;
48     for (auto it = threads_.begin(); it != threads_.end(); ++it) {
49       if (it->joinable()) {
50         std::cout << "thread " << it->get_id() << " join " << std::endl;
51         it->join();
52       }
53     }
54   }
55   ~ThreadPool() {}
56 
57  private:
58   //执行任务
59   void Execute() {
60     const auto thread_id = std::this_thread::get_id();
61     while (!stop_flag_) {
62       std::unique_lock<std::mutex> lock(task_mutex_);
63       if (task_queue_.size()) {
64         auto task = task_queue_.front();
65         task_queue_.pop_front();
66         lock.unlock();
67         std::cout << "thread id : " << thread_id << " start " << std::endl;
68         task();
69         std::cout << "thread id : " << thread_id << " stoped " << std::endl;
70       } else {
71         std::cout << "thread id : " << thread_id << " wait " << std::endl;
72         task_cond_.wait(lock, [&]() { return task_queue_.size(); });
73       }
74     }
75   }
76 };
复制代码

测试代码:

复制代码
int main(void) {
  ThreadPool thread_pool(11);
  //耗时函数
  auto cost_calcu = [](int cost_time) {
    std::this_thread::sleep_for(std::chrono::milliseconds(cost_time));
  };
  int cost_time = 0;
  for (int i = 0; i < 8; ++i) {
    cost_time = 1500 - i * 50;
    thread_pool.AddTask(std::bind(cost_calcu,cost_time));
  }
  cost_calcu(10000);//10s等待现有任务做完
  thread_pool.AddTask(std::bind(cost_calcu,2000));
  thread_pool.AddTask(std::bind(cost_calcu,1500));
  cost_calcu(10);//等10ms
  thread_pool.Halt();
  return 0;
}
复制代码

 

posted @   永驻的青春  阅读(52)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2020-06-17 opencv findContours函数
点击右上角即可分享
微信分享提示