C ++ Boost :: ASIO线程池问题

时间:2013-06-02 09:42:38

标签: c++ multithreading boost boost-asio threadpool

我刚刚为游戏服务器创建了我的线程池,但在编译我不知道如何解决的问题时遇到了一个错误。

错误:

  

Connection / CConnection.cpp:在lambda函数中:   Connection / CConnection.cpp:62:6:错误:没有捕获'this'   这个lambda函数

线程池声明:

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);
    });
}

有人可以告诉我在哪里,有什么问题吗?

1 个答案:

答案 0 :(得分:2)

我的猜测是asynchronousSendCConnection类中的一个函数。要调用对象中的函数,您必须捕获this

pool.enqueue([this] { ... });

如您所见,我删除了i的捕获,因为您在lambda中声明了一个本地i