1.写出一个单例
class Threadpool
{
private:
Threadpool(){}
static Threadpool threadpool;
public:
static Threadpool* getInstance(){ return &threadpool; }
};
Threadpool Threadpool::threadpool;
其中最容易忽视的一句是:Threadpool Threadpool::threadpool;
2.设计函数
public: void start() void addTask(task task_) private: void Runtask() //用于给start绑定
3.设计一个线程池,一个任务队列
vectorthreadList;//线程池 //任务队列 using task = function ; queue tasks;
4.使用Linux信号量
sem_t taskSem; sem_init(&taskSem, 0, 0); sem_post(&taskSem); sem_wait(&taskSem);
5.任务存放到任务队列中并使用 sem_post( ) 通知 sem_wait( ) ;
tasks.push(task_); sem_post(&taskSem); //信号量+1
6.收到通知,从任务队列中取出任务并执行
sem_wait(&taskSem); //收到通知开始执行 task task__; task__ = tasks.front(); //拿到第一个任务 tasks.pop(); //丢弃第一个任务 task__(); //执行第一个任务
7.开启线程池,往线程池里添加N个线程
for(int i = 0; i < 15; i++)
{
threadList.push_back(thread(&Threadpoll::Runtask, this));
}
8.附源码
#include#include #include #include #include #include #include using namespace std; sem_t taskSem; int poolSize = 10; class Threadpool { private: using task = function ; Threadpool() { sem_init(&taskSem, 0, 0); } static Threadpool threadpool; private: vector threadList; queue tasks; public: static Threadpool* getInstance(){ return &threadpool; } void addTask(task task_) { tasks.push(task_); sem_post(&taskSem); } void Runtask() { sem_wait(&taskSem); task task__; task__ = tasks.front(); tasks.pop(); task__(); } void start() { for(int i = 0; i < 15; i++) { threadList.push_back(thread(&Threadpool::Runtask, this)); } } }; Threadpool Threadpool::threadpool; //这句话很重要
9.测试
void func1()
{
cout<<"hello world"<start();
while(1)
{
sleep(2);
instance->addTask(func1);
}
return 0;
}



