skip to main | skip to sidebar
Showing posts with label boost. Show all posts
Showing posts with label boost. Show all posts

Tuesday, April 06, 2010

Bind illustrated

Asynchronous operations in Asio all expect a function object argument, the completion handler, which they invoke when the asynchronous operation completes. The signature of the handler depends on the type of operation. For example, a handler posted using io_service::post() must have the signature:

void handler();

while an asynchronous wait operation expects:

void handler(error_code ec);

and asynchronous read/write operations want:

void handler(error_code ec, size_t length);

Non-trivial applications will need to pass some context to the completion handler, such as a this pointer. One way to do this is to use a function object adapter like boost::bind, std::tr1::bind or (as of C++0x) std::bind.

Unfortunately, for many C++ programmers, bind represents a little bit of magic. This is not helped by the impenetrable compiler errors that confront you when you use it incorrectly. And, in my experience, the underlying concept (where some function arguments are bound up-front, while others are delayed until the point of call) can present quite a steep learning curve.

I have put together some diagrams to help explain how bind works. For clarity, I have taken a few liberties with C++ syntax (e.g. omitting the parameter types on the function call operator) and (over-)simplified bind's implementation. Finally, the examples are limited to those likely to be useful with Asio. Comments and suggestions welcome.


bind can be used to adapt a user-supplied function expecting one argument into a function object that takes zero arguments. The bound value (123 in this example) is stored in a function object and is automatically passed to the user-supplied function as required:


[ click images for full size ]

Binding an argument can be used to turn a class member function into a zero-argument function object. As you know, non-static member functions have an implicit this parameter. This means that an appropriate pointer needs to be bound into the function object:


Alternatively, the implicit this can be made explicit by adapting a member function into a function object taking one argument:


Function objects will often use both bound arguments and arguments supplied at the point of use. This can be done using member functions:


or non-member functions:


Sometimes the function object's point of use will supply arguments which are not required to call the target function. bind will automatically discard these surplus arguments:


The surplus argument(s) need not be the at the end of the function object signature:


Finally, bind allows you to the reorder arguments to adapt the target function to the necessary function object signature:

Friday, June 27, 2008

Mention in Stroustrup Interview

The A-Z of Programming Languages: C++, top of page 5:

Do you feel that resources like the boost libraries will provide this functionality/accessibility for C++?

Some of the boost libraries - especially the networking library - are a good beginning. The C++0x standard threads look a lot like boost threads. If at all possible, a C++ programmer should begin with an existing library (and/or tool), rather than building directly on fundamental language features and/or system threads.

Not by name, but hey! The rest of the interview is worth reading too. ;)

Friday, May 23, 2008

Boost.Asio vs Asio

Sometimes I am asked what the difference is between the (non-Boost) Asio and Boost.Asio packages I provide. Here is the definitive word on the subject, presented as a series of questions and answers.

What are the differences in the source code?

— Asio is in a namespace called asio::, whereas Boost.Asio puts everything under boost::asio::.

— The main Asio header file is called asio.hpp. The corresponding header in Boost.Asio is boost/asio.hpp. All other headers are similarly changed.

— Any macros used by or defined in Asio are prefixed with ASIO_. In Boost.Asio they are prefixed with BOOST_ASIO_.

— Asio includes a class for launching threads, asio::thread. Boost.Asio does not include this class, to avoid overlap with the Boost.Thread library

— Boost.Asio uses the Boost.System library to provide support for error codes (boost::system::error_code and boost::system::system_error). Asio includes these under its own namespace (asio::error_code and asio::system_error). The Boost.System version of these classes currently supports better extensibility for user-defined error codes.

— Asio is header-file-only and for most uses does not require linking against any Boost library. Boost.Asio always requires that you link against the Boost.System library, and also against Boost.Thread if you want to launch threads using boost::thread.

Where do I get a release package?

Asio is available for download from sourceforge, in a package named asio-X.Y.Z.tar.gz (or .tar.bz2 or .zip).

Boost.Asio is included in the Boost 1.35 distribution. It is also available as a separate package on sourceforge, named boost_asio_X_Y_Z.tar.gz. The latter is intended to be copied over the top of an existing Boost source code distribution.

Where are the source code repositories?

Asio uses a sourceforge-hosted CVS repository. Details of how to access it may be found here. It may also be browsed via the web.

Boost.Asio is checked into Boost's subversion repository.

How do you maintain both versions?

All development is done in the Asio CVS repository. I periodically convert the source into Boost format using a script called boostify.pl, and merge the changes into the Boost subversion repository.

Will Asio be discontinued now that Boost.Asio is included with Boost?

No. There are projects using Asio and they will continue to be supported. I also prefer to use Asio over Boost.Asio in my own projects, for the convenience of header-file-only and shorter namespaces.

Should I use Asio or Boost.Asio?

It depends. Here are some things to consider:

— If you (like me) prefer the convenience of header-file-only libraries then I'd suggest using Asio over Boost.Asio.

— If you must use a version of Boost older than 1.35 then Boost.Asio is not included. You can use Boost.Asio by copying it over the top of your Boost distribution (see above), but not everyone is comfortable doing this. In that case, I would suggest using Asio over Boost.Asio.

— I will be creating new versions of both the Asio and Boost.Asio packages on a faster release cycle than that followed by Boost. If you want to use the latest features you can still use Boost.Asio as long as you are happy to copy it over the top of your Boost distribution. If you don't want to do this, use Asio rather than Boost.Asio.

Can Asio and Boost.Asio coexist in the same program?

Yes. Since they use different namespaces there should be no conflicts, although obviously the types themselves are not interchangeable. (In case you're wondering why you might want to do this, consider a situation where a program is using third party libraries that are also using Asio internally.)

Sunday, March 30, 2008

739 days ago ...

... asio was accepted into Boost. Today you can find it as part of a Boost release. Woohoo!

Wednesday, August 08, 2007

Time Travel

Many event-driven programs involve state changes that are triggered according to the system clock. You might be coding for:

  • A share market that opens at 10:00am and closes at 4:00pm.

  • An off-peak phone billing rate that starts after 7:00pm.

  • An interest calculation that is run on the last day of every month.

The asio::deadline_timer class lets you handle this easily. For example:
using namespace boost::posix_time;
typedef boost::date_time::c_local_adjustor<ptime> local_adj;

...

asio::deadline_timer timer(io_service);

ptime open_time(second_clock::local_time().date(), hours(10));
timer.expires_at(local_adj::local_to_utc(open_time));
timer.async_wait(open_market);
There's a catch: to test that your timer events work correctly, you have to run your program at the right time of day. It usually isn't practical to sit around all day (or, worse, all year) waiting for the timers to expire.

Time Traits


You may have noticed that the asio::deadline_timer class is actually a typedef:
typedef basic_deadline_timer<boost::posix_time::ptime>
deadline_timer;
where the basic_deadline_timer class template is declared as follows:
template <
typename Time,
typename TimeTraits
= asio::time_traits<Time>,
typename TimerService
= deadline_timer_service<Time, TimeTraits> >
class basic_deadline_timer;
In the context of our problem, the most interesting template parameter is the second one: TimeTraits. An implementation of TimeTraits lets us customise the treatment of the template's Time parameter, and consequently the behaviour of the timer itself.

A TimeTraits class must implement an interface that matches the following:
class TimeTraits
{
public:
// The type used to represent an absolute time, i.e. the same
// as the Time template parameter to basic_deadline_timer.
typedef ... time_type;

// The type used to represent the difference between two
// absolute times.
typedef ... duration_type;

// Returns the current time.
static time_type now();

// Returns a new absolute time resulting from adding the
// duration d to the absolute time t.
static time_type add(time_type t, duration_type d);

// Returns the duration resulting from subtracting t2 from t1.
static duration_type subtract(time_type t1, time_type t2);

// Returns whether t1 is to be treated as less than t2.
static bool less_than(time_type t1, time_type t2);

// Returns a "posix" duration corresponding to the duration d.
static boost::posix_time::time_duration to_posix_duration(
duration_type d);
};
As you can see from the declaration of the basic_deadline_timer class template, Asio provides a default TimeTraits implementation called asio::time_traits<>.

Offsetting Now


To test our timer events at any time of our choosing, we simply need to change the definition of "now" using a custom TimeTraits class.

Since we want to use the same time types as the regular deadline_timer class, we'll start by reusing the default traits implementation:
class offset_time_traits
: public asio::deadline_timer::traits_type
{
};
The value returned by the now() function will be offset from the system clock by a specified duration:
class offset_time_traits
: public asio::deadline_timer::traits_type
{

private:
static duration_type offset_;
};
which is simply added to the system clock:
class offset_time_traits
: public asio::deadline_timer::traits_type
{
public:
static time_type now()
{
return add(asio::deadline_timer::traits_type::now(), offset_);
}

private:
static duration_type offset_;
};
Of course, we will also need to provide a way to set the offset, which can be done by setting an initial value for "now":
class offset_time_traits
: public asio::deadline_timer::traits_type
{
public:
static time_type now()
{
return add(asio::deadline_timer::traits_type::now(), offset_);
}

static void set_now(time_type t)
{
offset_ =
subtract(t, asio::deadline_timer::traits_type::now());
}

private:
static duration_type offset_;
};

Creating a Timer


To use our custom traits type with the basic_deadline_timer template, we simply need to add the following typedef:
typedef asio::basic_deadline_timer<
boost::posix_time::ptime, offset_time_traits> offset_timer;
To see the offset timer in action, let's create a timer to fire precisely at the start of the coming new year. So we don't have to wait until then, we'll set "now" to be just ten seconds prior to midnight:
offset_time_traits::set_now(
boost::posix_time::from_iso_string("20071231T235950"));

offset_timer timer(io_service);
timer.expires_at(
boost::posix_time::from_iso_string("20080101T000000"));
timer.async_wait(handle_timeout);

io_service.run();
When the program is run, it will take just ten seconds to complete.

Jumping Through Time


One feature not supported by the above solution is the ability to change the definition of "now" after the timers have been started. However, if your timer events are spread across a long period of time, then this is likely to be something you would want.

Let's say that the next timer does not expire for several hours, but in an attempt to speed things up we call set_now() to move to just seconds before. The problem with the above traits class is that the existing asynchronous wait operation does not know about the change to "now", and so will continue to run for the remaining hours.

Fortunately, Asio provides a way around this: by customising the to_posix_duration() function in our traits class.

The to_posix_duration() function is normally used to convert from a user-defined duration type to a type that Asio knows about (namely boost::posix_time::time_duration). The key point here is that this converted duration value is used by Asio to determine how long to wait until the timer expires. Furthermore, it doesn't matter if this function returns a duration that is smaller (even substantially so) than the actual duration. The timer won't fire early, because Asio guarantees that it won't expire until the following condition holds true:
!TimeTraits::less_than(Time_Traits::now(), timer.expires_at())
So, by adding the to_posix_duration() function to our traits class:
class offset_time_traits
: public asio::deadline_timer::traits_type
{
public:
static time_type now()
{
return add(asio::deadline_timer::traits_type::now(), offset_);
}

static void set_now(time_type t)
{
offset_ =
subtract(t, asio::deadline_timer::traits_type::now());
}

static boost::posix_time::time_duration to_posix_duration(
duration_type d)
{
return d < boost::posix_time::seconds(5)
? d : boost::posix_time::seconds(5);
}

private:
static duration_type offset_;
};
we can ensure that Asio detects changes to the offset within seconds.

Thursday, April 26, 2007

New home heating solution

For quite some time I have wanted to take a really good look at improving Boost.Asio's scalability across multiple processors. Unfortunately, getting unlimited access to this sort of hardware has been somewhat problematic. What I really needed was a decent multiprocessor box at home :)

The arrival of Intel's Clovertown quad core CPUs gave me the opportunity. The primary goal was to maximise parallelism while minimising the cost, and the lowest spec quad cores were cheap enough for me to justify spending the money. So, after months of thinking (and weeks of waiting for parts), last week I finally completed my home-built server.

Here are the headline specs:

  • Two Intel Xeon E5310 quad core processors (1.6 GHz)

  • Tyan Tempest i5000XL motherboard

  • 2GB DDR2-667 fully buffered ECC DIMMs

  • OCZ GameXStream 700W power supply (OK, OK, it's a little overpowered, but it was in stock!)

  • Other stuff like case, hard disk, DVD drive, video card and wireless LAN card

  • Lots of fans to provide soothing ambient noise

So far I have installed CentOS Linux 5 on it, but also plan to try Solaris 10 and FreeBSD. It seems pretty snappy.

Monday, January 15, 2007

Unbuffered socket iostreams

Boost.Asio includes an iostreams-based interface to TCP sockets, ip::tcp::iostream, for simple use cases. However, like the file iostreams provided by the standard library, ip::tcp::iostream buffers input and output data. This can lead to problems if you forget to explicitly flush the stream. For example, consider the following code to perform an HTTP request:
ip::tcp::iostream stream("www.boost.org", "http");
stream << "GET / HTTP/1.0\r\n"
<< "Host: www.boost.org\r\n"
<< "\r\n";

std::string response_line;
std::getline(stream, response_line);
...
The code will be stuck on the getline() call waiting for the response, because the request will still be sitting stream's output buffer. The correct code looks like this:
ip::tcp::iostream stream("www.boost.org", "http");
stream << "GET / HTTP/1.0\r\n"
<< "Host: www.boost.org\r\n"
<< "\r\n"
<< std::flush;
The std::flush will cause the stream to send the entire contents of its output buffer at that point.

Boost.Asio now supports an alternative solution: turn off the stream's output buffering. This is accomplished as follows:
ip::tcp::iostream stream("www.boost.org", "http");
stream.rdbuf()->pubsetbuf(0, 0);
stream << "GET / HTTP/1.0\r\n"
<< "Host: www.boost.org\r\n"
<< "\r\n";
Now you can send and receive to your heart's content, without having to worry about whether your message is stuck in the output buffer, but be warned: an unbuffered stream is a lot less efficient in terms of system calls. Don't use this feature if you care about performance.

Friday, November 10, 2006

Buffer debugging

Some standard library implementations, such as the one that ships with MSVC 8.0, provide a nifty feature called iterator debugging. What this means is that the validity of your iterators is checked at runtime. If you try to use an iterator that has been invalidated, you'll get an assertion. For example:
std::vector<int> v(1)
std::vector<int>::iterator i = v.begin();
v.clear(); // invalidates iterators
*i = 0; // assertion!
Boost.Asio now takes advantage of this feature to add buffer debugging. Consider the following code:
void dont_do_this()
{
std::string msg = "Hello, world!";
asio::async_write(sock, asio::buffer(msg), my_handler);
}
When you call an asynchronous read or write you need to ensure that the buffers for the operation are valid until the completion handler is called. In the above example, the buffer is the std::string variable msg. This variable is on the stack, and so it goes out of scope before the asynchronous operation completes. If you're lucky, your application will crash. Often you will get random failures.

With the new buffer debug checking, however, Boost.Asio stores an iterator into the string until the asynchronous operation completes, and then dereferences it to check its validity. In the above example you get an assertion failure just before Boost.Asio tries to call the completion handler.

This feature has only been tested with MSVC 8.0 so far, but it should work with any other implementation that supports iterator debugging. Obviously there's a performance cost to this checking, so it's only enabled in debug builds. You can also explicitly disable it by defining BOOST_ASIO_DISABLE_BUFFER_DEBUGGING (or ASIO_DISABLE_BUFFER_DEBUGGING if you're using standalone asio).

Saturday, October 07, 2006

FreeBSD support

Asio has now been tested successfully on FreeBSD 6.0, and should support FreeBSD 5.5 and later. FreeBSD 5.4 and earlier are not supported since, according to the man pages, getaddrinfo is not thread-safe.

Tuesday, September 26, 2006

SSL password callbacks

On the weekend I made some changes to asio to support password callbacks for SSL. There is a new function on the asio::ssl::context class called set_password_callback(), which takes a function object with the following signature:
std::string password_callback(
std::size_t max_length,
ssl::context::password_purpose purpose);
The callback must return the password as a string. The max_length argument indicates the maximum allowable length of the password, and if the returned string is longer it will be truncated. The context::password_purpose type is an enum with values for_reading and for_writing. In most cases you won't need to use the max_length or purpose arguments, and if you use boost::bind() to create the function object you can just leave them off. For example, the SSL server sample included with asio now has the following:
context_.set_password_callback(
boost::bind(&server::get_password, this));

...

std::string get_password() const
{
return "test";
}
The final thing to note is that the password callback needs to be set before calling any ssl::context functions that load keys, such as use_private_key_file().
Subscribe to: Comments (Atom)
 

AltStyle によって変換されたページ (->オリジナル) /