boost::bind 成员函数在它自己的成员函数中作为参数

boost::bind member function as argument inside its own member function

我正在学习 boost asio 教程 (https://www.gamedev.net/blogs/entry/2249317-a-guide-to-getting-started-with-boostasio/)。

现在我想将本教程的某些方面转换为 class,以详细了解代码每个部分的实际情况。所以我试图加强绑定:

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:\Boost\boost_1_75_0\boost_1_75_0\boost\bind\bind.hpp  227 

如果我按照文档将其放入主循环,它工作正常,它甚至将成员变量 fine 作为参数:

LDserver s1;
for (int i = 0; i <= 2; i++)
    {
        s1.worker_threads.create_thread(boost::bind(&workerThread, s1.io_service));
    }

通过注释我 100% 确定,因为它没有采用我将 worketThread() 成员函数作为正确语法的方式,但是在花了 2 天的时间尝试找到答案之后,我希望这里有人可以赐教。

问题在于线程函数不是静态的,因此它需要 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
    }
};