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.
This code would explain what I want to do.. but my question is how can I
do it or if there are already some wrappers out there that I can use for
boost threads?
Sample code :
----- MyThread.h -----
#include "myRunnable.h"
#include
On 2/6/06, boostguy@kapiladhanvi.com
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.
And *why* would you want something like this? [snip] -- Felipe Magno de Almeida
boostguy@kapiladhanvi.com 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. :-)
participants (3)
-
boostguyï¼ kapiladhanvi.com
-
Felipe Magno de Almeida
-
Peter Dimov