boost-asio在两个线程c++之间进行通信

boost asio communicate between two threads c++

本文关键字:之间 c++ 通信 线程 两个 boost-asio      更新时间:2023-10-16

我正在使用boost asio创建客户端和服务器应用程序。情况是,我创建了一个用于实例化服务器对象的线程,而主线程将实例化客户端对象。这些对象中的每一个都有自己的io_service,它们在两个线程中独立运行。我现在需要的是,在不使用客户端和服务器之间的套接字的情况下,将一些信息从服务器对象传递回主线程。我需要传递的信息是服务器使用端口(0)获取的端口和服务器从客户端接收的请求。

有很多太少的代码,但这里是:

#include <boost/asio.hpp>
#include <boost/optional.hpp>
#include <boost/thread.hpp>
#include <iostream>
using namespace boost::asio;
struct asio_object {
  protected:
    mutable io_service io_service_;
  private:
    boost::optional<io_service::work> work_ { io_service::work(io_service_) };
    boost::thread th    { [&]{ io_service_.run(); } };
  protected:
    asio_object() = default;
    ~asio_object() { work_.reset(); th.join(); }
};
struct Client : asio_object {
  public:
    void set_message(std::string data) {
        io_service_.post([=]{ 
                message = data; 
                std::cout << "Debug: message has been set to '" << message << "'n";
            });
    }
  private:
    std::string message;
};
struct Server : asio_object {
    Client& client_;
    Server(Client& client) : client_(client) {}
    void tell_client(std::string message) const {
        client_.set_message(message);
    }
};
int main()
{
    Client client;
    Server server(client);
    server.tell_client("Hello world");
}

(这是一个有点疯狂的猜测,因为你没有准确地描述你的问题)