Linux多线程编程工具库liblmp_tool github: https://github.com/Dwyane05/liblmp_tool
使用条件变量和互斥锁实现线程池:
头文件:
/*
* Use of this source code is governed by a BSD-style license
* that can be found in the License file.
*
* ThreadPool.h
* Created on: May 30, 2019
* Author: cuiyongfei
*/
#ifndef LMP_TOOL_THREADPOOL_H
#define LMP_TOOL_THREADPOOL_H
#include "Condition.h"
#include "Mutex.h"
#include "Thread.h"
#include "Common.h"
#include <deque>
#include <vector>
namespace lmp_tool
{
class ThreadPool : noncopyable
{
public:
typedef std::function<void ()> Task; //任务
explicit ThreadPool(const string& nameArg = string("ThreadPool"));
~ThreadPool();
// Must be called before start().
void setMaxQueueSize(int maxSize) { maxQueueSize_ = maxSize; } //设置队列大小
void setThreadInitCallback(const Task& cb) //回调任务
{ threadInitCallback_ = cb; }
void start(int numThreads); //启动 参数是线程数
void stop(); //停止
const string& name() const
{ return name_; }
size_t queueSize() const;
// Could block if maxQueueSize > 0
// There is no move-only version of std::function in C++ as of C+