sams
sams

Reputation: 1

boost asio communicate between two threads c++

I am using boost asio to create a client and server application. The situation is I have created a thread for instantiating the server object while the main thread would be instantiating the client object. Each of these objects have their own io_service which run independent of each other in the two threads.What I need now is I want to communicate some information from the server object back to the main thread without using the socket between the client and server. The information which I need to pass is the port which the server has acquired using port(0) and the request which the server has received from the client.

Upvotes: 0

Views: 1326

Answers (1)

sehe
sehe

Reputation: 392893

There's a lot too little code, but here goes:

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

(This is a bit of a wild guess, as you didn't exactly describe your question in exact terms)

Upvotes: 1

Related Questions