alldroll
alldroll

Reputation: 69

create socket after io_service run

In all examples of using boost, usually people do the following

boost::asio::io_service io_service;
tcp::socket s1(io_service);
tcp::socket s2(io_service);
io_service.run();

But i am writing class that already has running in thread io_service and it has to create sockets with this io_service. And there is my question. How to make it thread safety?

class MySocket
{
private:

    boost::asio::io_service* ioService;
    tcp::socket* socket;
public:
     MySocket(boost::asio::io_service* nioService,
              tcp::resolver::iterator endpoint_iterator):
    ioService(nioService)
    {
        socket = new tcp::socket(*ioService);
    }
     ~MySocket();
};

SocketHandler handler;
handler.run(); //run io_service in thread
MySocket* s1 = handler.createSocket("localhost", "80");
//do something
MySocket* s2 = handler.createSocket("localhost", "81");
//dododo
handler.destroySocket(s1);
handler.destroySocket(s2);

Upvotes: 0

Views: 483

Answers (1)

Ivan
Ivan

Reputation: 2057

You can create new sockets at any time with boost::asio.

io_service::run() blocks until working queue is empty. If it there is no work in the queue - the function returns immediately. That's why people usually add work to it (create timers, bind sockets, etc) prior to io_service::run().

BTW: I don't recommend doing this way:

MySocket* s1 = handler.createSocket("localhost", "80");
...
handler.destroySocket(s1);

use RAII-objects (smart pointers) instead.

Upvotes: 1

Related Questions