Wednesday, June 25, 2008

asio::io_service::reset hint

I can advise to call asio::io_service::reset before each call of asio::io_service::run:
This function must be called prior to any second or later set of invocations of the run(), run_one(), poll() or poll_one() functions when a previous invocation of these functions returned due to the io_service being stopped or running out of work. This function allows the io_service to reset any internal state, such as a "stopped" flag.


This may prevent you from some stupid errors.

Tuesday, June 24, 2008

asio::windows::basic_stream_handle - 2

Also, we can 'hack' windows::basic_stream_handle. If we add following code info file win_iocp_handle_service.hpp after line 691 and basic_stream_handle will works as I expect =)

I don't understand all reasons why asio developers chose different way for solving this 'problem'.

ptr.get()->Offset = boost::uint64_t (handler.total_transferred_) & 0xFFFFFFFF;
ptr.get()->OffsetHigh = (boost::uint64_t (handler.total_transferred_) >> 32) & 0xFFFFFFFF;
_Winnie C++ Colorizer

asio::async_read and asio::windows::basic_stream_handle

Huh.

Last few days I play with asio. I try to read files asynchronously using asio, but asio doesn’t work properly (I think) in this case.
For example, simple code (see below) doesn’t work as I expect.
asio::windows::basic_stream_handle<> handle_;
asio::streambuf buf_;

asio::async_read (stream_, buf_, complete_condition_, handler_);
_Winnie C++ Colorizer


I expect that asio::async_read reads whole file into buffer buf_, but instead this asio fills buffer with block of data read from begin of file.

Alex advise me try version from cvs.sourceforge. In that version windows::basic_stream_handle doesn’t work properly too, but cvs version contains windows::basic_random_access_handle. Using this class we can build working stream that allow us read files sequentially or randomly. For example we can build following sequential stream:
struct random_handle_wrapper
{
random_handle_wrapper (asio::io_service &io_service, HANDLE file)
: handle_ (io_service, file)
, file_ (file)
, transfered_ (0)
{

}

template <typename MutableBufferSequence, typename ReadHandler>
void async_read_some(const MutableBufferSequence& buffers, ReadHandler handler)
{
handle_.async_read_some_at (transfered_, buffers, handler);
}

void move_fwd (size_t transfered)
{
transfered_ += transfered;
}

asio::windows::basic_random_access_handle<> handle_;
HANDLE file_;
boost::uint64_t transfered_;
};
_Winnie C++ Colorizer


And read_handler that uses this stream:
void read_handler (asio::error_code ec, size_t transferred)
{
std::cout << std::string (data_.c_array(), data_.c_array() + transferred);
stream_.move_fwd (transferred);
asio::async_read (stream_, buf_, complete_condition_, handler_);
}
_Winnie C++ Colorizer