|
#pragma once
typedef boost::function<void()> VoidFunc;
class FuncArray
{
public:
FuncArray(void)
{
funcvec.reserve(4096);
}
void post(VoidFunc func)
{
asio::detail::mutex::scoped_lock lock(mtx);
funcvec.push_back(func);
}
void handle()
{
std::vector<VoidFunc> curfuncvec;
{
asio::detail::mutex::scoped_lock lock(mtx);
curfuncvec.swap(funcvec);
}
for(size_t i=0;i<curfuncvec.size();i++)
{
curfuncvec[i]();
}
}
~FuncArray(void){}
std::vector<VoidFunc> funcvec;
asio::detail::mutex mtx;
};
#pragma once
#include "funcarray.h"
class UvLoopWorker
{
public:
UvLoopWorker(void);
virtual ~UvLoopWorker(void);
//启动线程
int start()
{
new asio::thread(boost::bind(&UvLoopWorker::run,this));
return 0;
}
//在他的线程里面执行一个函数
void post(VoidFunc func)
{
_fa.post(func);
notify();
}
virtual void on_start_loop(){}
protected:
void notify()
{
int r = uv_async_send(&_async);
}
int run();
static void async_cb(uv_async_t* handle)
{
UvLoopWorker *pthis=(UvLoopWorker *)handle->data;
pthis->_fa.handle();
}
uv_async_t _async;
uv_loop_t *_loop;
FuncArray _fa;
};
class UvLoopWorkerMgr
{
public:
static void init(int numofitems);
static std::vector<UvLoopWorker *> wrkers;
void post(VoidFunc &func)
{
static int id=0;
id++;
post(func,id);
}
void post(VoidFunc &func,int idx)
{
int nitem=idx % wrkers.size();
return wrkers[nitem]->post(func);
}
};
|
|