gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:17:44 25 4
gpt4 key购买 nike

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

错误:

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

有人能告诉我哪里有问题吗?

最佳答案

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

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

如您所见,我已经删除了 i 的捕获,因为它不是必需的,因为您在 lambda 中声明了本地 i

关于C++ Boost::ASIO 线程池问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16881556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com