c++11多线程线程池

  1. threadPool.h 头文件
    #pragma once
    #include<iostream>
    #include<stdlib.h>
    #include<vector>
    #include<thread>
    #include<mutex>
    #include<functional>
    #include<queue>
    
    using namespace std;
    
    class ThreadPool
    {
    public:
        typedef function<void()> Task;
        ThreadPool();
        ~ThreadPool();
    private:
        std::vector<std::thread> threads;
        queue<Task> task;
        mutex _mutex;
        condition_variable cond;
        bool done;
        bool isEmpty;
        bool isFull;
        size_t nthreads;
    public:
        void start(int n);
        void runtask();
        void addTask(const Task& f);
        void finish();
    };
    
  2. threadPool.cpp
    #include "ThreadPool.h"
    
    ThreadPool::ThreadPool():isEmpty(true),isFull(false),done(false)
    {
    
    }
    
    ThreadPool::~ThreadPool()
    {
    }
    
    void ThreadPool::start(int n)
    {
    	(*this).nthreads = n;
    	for (int i = 0; i < n; i++)
    	{
    		threads.push_back(thread(&ThreadPool::runtask, this));
    	}
    }
    
    void ThreadPool::runtask()
    {
    	while (!done)
    	{
    		unique_lock<mutex> lk(_mutex);
    		while (isEmpty)
    		{
    			cond.wait(lk);
    		}
    		if (done) break;
    		Task ta;
    		ta = move(task.front());
    		task.pop();
    		if (task.empty()) {
    			isEmpty = true;
    		}
    
    		isFull = false;
    		ta();
    		cond.notify_one();
    	}
    }
    
    void ThreadPool::addTask(const Task& f)
    {
    	if (!done)
    	{
    		unique_lock<mutex> lk(_mutex);
    		while (isFull)
    		{
    			cond.wait(lk);
    		}
    
    		task.push(f);
    		if (task.size() == nthreads)
    			isFull = true;
    		cout << "Add a task" << endl;
    		isEmpty = false;
    		cond.notify_one();
    	}
    }
    
    void ThreadPool::finish()
    {
    	if (!done)
    	{
    		//unique_lock<mutex> lk(_mutex);
    		done = true;
    		cond.notify_all();
    		for (int i=0;i<nthreads;i++)
    		{
    			threads[i].join();
    		}
    	}
    	
    }
    
    1. main.cpp
      #include <iostream>
      #include "ThreadPool.h"
      
      void func(int i)
      {
          cout << "task finish" << "----------->" << i << endl;
      }
      
      int main()
      {
          ThreadPool p;
          p.start(4);
          int i = 0;
          while (i<100)
          {
              i++;
              //
              this_thread::sleep_for(chrono::milliseconds(1));
              auto task = bind(func, i);
              p.addTask(task);
          }
          p.finish();
          return 0;
      }
      
      亲测无bug。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值