0
点赞
收藏
分享

微信扫一扫

threadcxx

#include <iostream>

#include <thread>

#include <queue>

#include <mutex>

#include <condition_variable>

#include <vector>

#include <functional>

using namespace std;


class ThreadPool{

   vector<thread> threads;

   queue<function<void()>> tasks;

   condition_variable cond;

   mutex m;

   bool exited = false;

public:

   ThreadPool(int num){

auto routine = [this](){

    while(true){

        unique_lock<mutex> lock(m);

        while(tasks.empty() && !exited) cond.wait(lock);

        if(exited) break;

        auto func = tasks.front();

        tasks.pop();

        lock.unlock();

        func();

   }      

};

    for(int i=0;i<num;++i){

    // thread t(routine);

    // threads.emplace_back(move(t));

    // threads.emplace_back(thread(routine));

    threads.emplace_back(thread{routine});

}

   }

   ~ThreadPool(){

    exited = true;

cond.notify_all();

for(auto& thread:threads){

    thread.join();

}

   }

   ThreadPool(const ThreadPool&) = default;

   ThreadPool& operator=(const ThreadPool&) = default;


   void AddTask(function<void()> func){

 lock_guard<mutex> guard(m);

 tasks.push(func);

 cond.notify_one();

        // signal

   }


};


int main(){

   mutex m;

   auto test = [&m](){

this_thread::sleep_for(2s);

lock_guard<mutex> guard(m);

       cout << this_thread::get_id() << " do something..." << endl;

   };


   ThreadPool pool(5);


   for(int i=0;i<15;++i){

       pool.AddTask(test);

   }

   this_thread::sleep_for(10s);

}

举报
0 条评论