Boost: Thread timing and timeouts

Boost.Thread has the ability to use timeouts for obtaining mutex resources or even just blocking a thread with the sleep() method.  Creating a timeout is, thankfully, a very easy task. All one needs to know is that the Boost.Thread library takes timeout parameters in the form of boost::system_time (as of Boost 1.35).  This is actually just a simple typedef to a POSIX data structure in the Boost.DateTime library.  From boost/thread/thread_time.hpp:

typedef boost::posix_time::ptime system_time;

To create a simple timeout, the following code will usually suffice:

boost::system_time timeout = boost::get_system_time() + boost::posix_time::milliseconds(n);

The vaule for n is simply an integer value, perhaps randomly generated? There is no need to dig into the large and versatile Boost.DateTime library, and with boost::system_time there is no longer a need to use boost::xtime unless working with an older code base that has yet to be refactored.  With random time period generation and timeouts covered, we are now ready to move onto exploring some multithreaded code.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s