Boost logo

Boost Users :

Subject: Re: [Boost-users] [asio] [thread] Code review for correct use of boost sockets and threads
From: Niklas Angare (li51ckf02_at_[hidden])
Date: 2011-07-05 20:27:14


"Konrad Reiche" wrote:
> So basically I've written a small class which is suppossed to take
> messages and send them asynchronously.
...
> 1. The constructor launches the threads,

You create the boost::thread object on the constructor stack which will
result in the thread becoming detached when the constructor returns. This is
probably very bad if you ever intend to have your application exit cleanly.
You should always join() with any threads you create.

> Is there any possible problem which
> could occur due to buffer or thread issues? Because sometimes the
> messages are not processed until the end and when they are processed
> they are corrupted.

It appears as if your messageQueue object is used both by the functions that
run in the thread you created (for example handle_write) and the await
function which I assume runs in the main thread. That's a race condition
(threading bug). You must protect all variables shared between threads with
locks. You may want to skip threading and just do everything on the main
thread. It should be perfectly feasible to do that with Asio.

> When the host I am connecting to does not listen on the port I am
> connecting to, I don't receive an error by the functions I am using. So
> the messages are queued up and nothing happens. I don't know why. Have I
> forgot any checking whether the connection could be established?

Your handle_connect function which is called with the result of the
connection attempt doesn't do anything. You should handle any errors there.
You shouldn't try to send anything on the socket until after the connect
succeeds.

You may get more responses to Asio questions on the Asio mailing list.

Regards

Niklas Angare


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net