Boost logo

Boost :

From: Matthew Herrmann (matthew.herrmann_at_[hidden])
Date: 2006-11-05 20:23:58


Hi All,

I'm having some difficulty implementing a tcp client using boost::asio.
I am calling tcp::socket::read on one thread, and then calling
tcp::socket::close on another thread. I expected the blocking read()
call to return with boost::asio::error::eof upon closing but it doesn't.
I then tried using async_read, but that was never called. To
troubleshoot, I converted my connect function to async_connect and found
that the callback there was not being called either.

I think I have traced the behaviour down to something rather basic but
counterintuitive. Any asynchronous functions posted after the
io_service::run method starts are never called. All of the example code
seems to avoid this problem by making the run call the last in the
sequence, and then daisy-chaining new callbacks from within old ones. In
my case, I need to start the io_service before I call async_connect, I
don't see how this can work. I don't know if this is related to my
original read/close problem, but it seems to rule out my workaround.

Here is an example snippet I expected to work. To my understanding, the
following snippet should print out "test_fn()", but the function is
never called. If I post test_fn before starting the thread, it works as
expected.

static void test_fn()
{
    std::cout << "test_fn()" << std::endl;
}

int main()
{
    boost::asio::io_service io_service;
    boost::thread(boost::bind(boost::asio::io_service::run, &io_service));
    sleep(1);
    io_service.post(boost::bind(&test_fn));
    while(true)
    { sleep(1); }
    return 0;
}

My understanding of io_service was that it essentially modelled a
functor message queue, running on the thread(s) from which run() was
called, onto which all asynchronous notifications are posted. I'm using
a recent version of linux.

Have I missed something obvious? I just want to implement a basic TCP
client with the capability to read/write bytes, and record
connect/disconnect.

Many thanks in advance,

Matthew

-- 
_________________________
Matthew Herrmann
matthew.herrmann_at_[hidden]

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk