#pragma once
#include"noncopyable.h"
#include<string>
#include<memory>
#include<vector>
#include<functional>
class EventLoopThread;
class EventLoop;
class EventLoopThreadPool:noncopyable
{
public:
using ThreadInitCallback = std::function<void(EventLoop*)>;
EventLoopThreadPool(EventLoop*baseLoop,const std::string &nameArg);
~EventLoopThreadPool();
void setThreadNum(int numThreads) { numThreads_=numThreads; }
void start(const ThreadInitCallback &cb= ThreadInitCallback());
EventLoop *getNextLoop();
std::vector<EventLoop*> getAllLoops();
bool started ()const { return started_; };
const std::string name() const{ return name_; };
private:
EventLoop *baseLoop_;
std::string name_;
bool started_;
int numThreads_;
int next_;
std::vector<std::unique_ptr<EventLoopThread>>threads_;
std::vector<EventLoop*>loops_;
};
#include"EventLoopThreadPool.h"
#include"EventLoopThread.h"
#include<memory>
#include<vector>
#include"Logger.h"
EventLoopThreadPool::EventLoopThreadPool(EventLoop*baseLoop,const std::string &nameArg)
: baseLoop_(baseLoop)
, name_(nameArg)
, started_(false)
, numThreads_(0)
, next_(0)
{
}
EventLoopThreadPool::~EventLoopThreadPool()
{}
void EventLoopThreadPool::start(const ThreadInitCallback &cb)
{
started_=true;
for(int i=0;i<numThreads_;++i)
{
char buf[name_.size()+32]={0};
snprintf(buf,sizeof buf,"%s%d",name_.c_str(),i);
EventLoopThread *t = new EventLoopThread(cb,buf);
threads_.push_back(std::unique_ptr<EventLoopThread>(t));
loops_.push_back(t->startLoop());
}
if(numThreads_==0&&cb)
{
cb(baseLoop_);
}
}
EventLoop* EventLoopThreadPool::getNextLoop()
{
EventLoop *loop = baseLoop_;
if (!loops_.empty())
{
loop = loops_[next_];
++next_;
if (next_ >= loops_.size())
{
next_ = 0;
}
}
return loop;
}
std::vector<EventLoop*> EventLoopThreadPool::getAllLoops()
{
if(!loops_.empty())
{
return loops_;
}
else
{
return std::vector<EventLoop*>(1,baseLoop_);
}
}