我正在学习一个教程(https://www.gamedev.net/blogs/entry/2249317-a-guide-to-getting-started-with-boostasio/)用于助推asio。
现在,我想将本教程的一些方面转换为一个类,以了解更多关于代码每个部分中实际发生的事情。所以我正试图增强绑定:
class LDserver
{
public:
void workerThread(boost::shared_ptr<boost::asio::io_service> io_service)
{
io_service->run();
}
void createThreads()
{
this->worker_threads.create_thread(boost::bind(&LDserver::workerThread, this->io_service));
}
~LDserver() = default;
boost::thread_group worker_threads;
boost::shared_ptr<boost::asio::io_service> io_service = boost::make_shared<boost::asio::io_service>();
boost::shared_ptr<boost::asio::io_service::work> work = boost::make_shared<boost::asio::io_service::work>(*this->io_service);
boost::asio::io_service::strand strand = boost::asio::io_service::strand(*this->io_service);
};
在文档之后,它指出这应该是正确的语法,而不是作为一个参数。但我却收到了来自boost的错误消息::bind库。
Severity Code Description Project File Line Suppression State
Error C2440 'return': cannot convert from 'R (__cdecl &)' to 'R' LockManager C:Boostboost_1_75_0boost_1_75_0boostbindbind.hpp 227
如果我遵循文档并将其放入主循环中,它会很好地工作,甚至会将成员变量fine作为参数:
LDserver s1;
for (int i = 0; i <= 2; i++)
{
s1.worker_threads.create_thread(boost::bind(&workerThread, s1.io_service));
}
通过评论,我百分之百肯定,因为这并不需要我将worketThread((成员函数语法化为正确的函数,然而,在花了两天的时间尝试并找到答案后,我希望这里的人能启发我。
问题是线程函数不是静态的,因此它需要this
(LDServer*(的参数。或者你可以把它做成static
:
static void workerThread(boost::shared_ptr<ba::io_service> io_service) {
io_service->run();
}
void createThreads() {
worker_threads.create_thread(
boost::bind(&LDserver::workerThread, io_service));
}
然而,所有猖獗的动态分配、共享所有权和手动线程,以及boost-bind/shared_ptr而不是标准库,都是代码气味。如果你正在使用VeryOldOrBadBook(TM(来学习这一点,请比较:
#include <boost/asio.hpp>
namespace net = boost::asio;
class LDserver : public std::enable_shared_from_this<LDserver> {
using executor_type = net::thread_pool::executor_type;
net::thread_pool _ctx{1}; // one thread please
net::strand<executor_type> _strand{_ctx.get_executor()};
public:
~LDserver() {
_ctx.join(); // don't forget to join your threads anyway
}
};