我剛剛爲遊戲服務器創建了我的線程池,但在編譯我不知道如何修復時遇到了一個錯誤。C++ Boost :: ASIO線程池問題
錯誤:
Connection/CConnection.cpp: In lambda function: Connection/CConnection.cpp:62:6: error: 'this' was not captured for this lambda function
線程池聲明:
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);
});
}
有人能告訴我在哪裏,什麼是問題呢?
您確定要將線程池作爲'handle'函數中的普通局部變量嗎?記住它在'handle'函數返回時會被破壞。 –
是的,我知道,我只是把它放到這裏來編譯測試。 –