我只是为游戏服务器创建了线程池,但是在编译我不知道如何解决的内容时遇到了一个错误。
错误:
线程池声明:
class Worker {
public:
Worker(ThreadPool &s) : pool(s) { }
void operator()();
private:
ThreadPool &pool;
};
// the actual thread pool
class ThreadPool {
public:
ThreadPool(size_t);
template<class F>
void enqueue(F f);
~ThreadPool();
private:
// need to keep track of threads so we can join them
std::vector< std::unique_ptr<boost::thread> > workers;
// the io_service we are wrapping
boost::asio::io_service service;
boost::asio::io_service::work working;
friend class Worker;
};
template<class F>
void ThreadPool::enqueue(F f)
{
service.post(f);
}
功能用什么:
void CConnection::handle()
{
int i = 0;
ThreadPool pool(4);
pool.enqueue([i]
{
char * databuffer;
databuffer = new char[16];
for(int i = 0;i<16;i++)
{
databuffer[i] = 0x00;
}
databuffer[0] = 16;
databuffer[4] = 1;
databuffer[8] = 1;
databuffer[12] = 1;
asynchronousSend(databuffer, 16);
});
}
有人可以告诉我问题在哪里吗?
最佳答案
我的猜测是asynchronousSend
是CConnection
类中的一个函数。要在对象中调用函数,您必须捕获this
:
pool.enqueue([this] { ... });
如您所见,由于您在lambda中声明了本地
i
,因此我删除了不需要的i
捕获。关于c++ - C++ Boost::ASIO线程池问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16881556/