Boost logo

Boost Users :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2006-02-06 16:37:19


boostguy_at_[hidden] wrote:
> Hi all,
> I am trying to write a generalized object oriented wrapper for thread
> library implementation of Boost.
>
> Boost threads take a function name as an argument when creting a
> thread. I would like create a warpper in C++ which would in some
> respects mimic JAVA and have a runnable interface which an threaded
> application would implement.

Given:

struct Runnable
{
    virtual ~Runnable() {}
    virtual void run() = 0;
};

you can execute a runnable in a thread by using the following function:

void execute_in_thread( boost::shared_ptr<Runnable> pr )
{
    boost::thread th( boost::bind( &Runnable::run, pr ) );
}

There is no need to use a Runnable interface with Boost.Threads, though; the
same pattern will work for any class, not just those derived from Runnable:

template<class Runnable> void execute_in_thread( boost::shared_ptr<Runnable>
pr )
{
    boost::thread th( boost::bind( &Runnable::run, pr ) );
}

And in case your run() function takes arguments or is named differently
(X::start, say), you can just write the line

    boost::thread th( boost::bind( &X::start, pr, 5 ) );

in your code instead of calling execute_in_thread.

Once you get to this point, you might consider replacing the class with a
function taking the same arguments you've passed to the constructor,
replacing

    shared_ptr<X> px( new X( 1, 2 ) );
    boost::thread th( boost::bind( &X::run, pr ) );

with just

    boost::thread th( boost::bind( my_thread_function, 1, 2 ) );

if you don't need to access X from outside its thread.

Or you can stick to the Java style if you like it better or find it more
natural. :-)


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