Bytemaster's Boost Libraries
Quick Start
Boost.CMT

Asynchronous Calls in Current Thread

Here is a simple benchmark program that performs an asynchornous operation and waits on the result.

    using namespace boost::cmt;

    int hello(const std::string& world ) {
        return world.size(); 
    }

    void bench() {
        ptime start = microsec_clock::universal_time();
        int sum = 0;
        for( uint32_t i = 0; i < 1000; ++i ) 
            sum += async<int>( boost::bind(hello, "world"), "hello_func" ).wait();
        ptime end = microsec_clock::universal_time();
        slog( "%1% calls/sec", (1000.0/((stop-start).total_microseconds()/1000000.0)) );
    }

    int main( int argc, char** argv ) {
        async( bench );
        boost::cmt::exec(); 
    }

In the code above, boost::cmt::async<int>(functor) takes a functor that takes 0 parameters and returns an integer. The result is a boost::cmt::future<int> which will not block until wait() is called.

Asynchronously wait on a Signal

This example shows how a task can wait on an event triggered by a boost::signal.

    boost::signal<void(std::string)> test_signal;
   
    void delay()
    {
        boost::cmt::usleep(2000000);
        test_signal("hello world!");
    }

    void wait_on_signal() {
        std::string rtn = boost::cmt::wait(test_signal);
    }

    int main( int argc, char** argv ) {
         async( delay );
         async( wait_on_signal );
         boost::cmt::exec(); 
    }

Inter-thread Invocations

Sometimes you really want things to happen in parallel on multiple real CPU cores. In this case you will need to have some kind of inter-thread synchronization. Boost.CMT enables lock-free interthread communication by posting tasks to an appropriate event queue and returning a boost::cmt::future.

        boost::cmt::thread* t = boost::cmt::thread::create();
        future<int> fut_val = t->async( boost::bind( hello, "world" ) );
        int val = t->sync( boost::bind( hello, "world" ) );
        int val2 = fut_val.wait();

In this example I introduce a new method, thread::sync<rtn>(functor), which is identical to thread::async<rtn>(functor).wait() except that it can avoid extra heap allocations because it knows that the boost::cmt::promise's life will not excede the scope of thread::sync and therefore the promise can be allocated on the stack.

Yielding and Sleeping

The current task can either yield and allow other tasks to run before returning or it can sleep for an specific amount of time while allowing other tasks to run.

        boost::cmt::usleep(100000/*us*/);
        boost::cmt::yield();

        // or the more verbose...
        boost::cmt::thread::current().usleep(10000);
        boost::cmt::thread::current().yield();

You can only yield or sleep for the current thread. If there are no other tasks ready to run then yield() returns immediately.

 All Classes Namespaces Files Functions Variables Typedefs Defines