【问题标题】:boost asio communicate between two threads c++两个线程c ++之间的boost asio通信
【发布时间】:2014-11-08 12:41:35
【问题描述】:

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

【问题讨论】:

  • 很难弄清楚你想要什么。我已经将一些示例代码拼凑在一起。如果没有回答,请使用它为您的问题创建 SSCCE。
  • 这是一个非常模糊的问题。通常使用多个io_service 对象的应用程序可以通过posting work 到各自的io_service 相互通信。

标签: c++ multithreading boost boost-asio


【解决方案1】:

代码太少了,但这里有:

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

(这有点疯狂,因为您没有准确地描述您的问题)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    相关资源
    最近更新 更多