
Sean Kelly wrote:
scott wrote:
very briefly, the boost model treats threads as a resource (fair enough to :-) and submits code fragments for asynchronous execution. in the alternate model, threads come about as a consequence of instantiating final (a la java) objects.
This is how I've always dealt with threads. I think you can create the same effect with Boost threads if you really want to however:
struct A { boost::thread* t; A() { t = new boost::thread( *this ); } void operator()() { ... } };
The only irritating thing is that Boost threads need to be passed the executing object on construction so you need to allocate it dynamically.
I'll admit I do prefer the inheritance model in most cases. Perhaps a new class called thread_base could be added so both methods are available? It would be a pretty simple addition.
Did you have something like this in mind: // untested code class thread_base : noncopyable { public: thread_base() : pThread_( new boost::thread( *this ) ) {} ~thread_base() { pThread_->join(); delete pThread_; } private: virtual void operator()() = 0; friend class boost::thread; boost::thread * pThread_; }; ? If yes, how do you ensure that operator() is not called before the subclass object is fully constructed? Moreover, when destructing the subclass object we have the problem that the subclass portion of the thread object is destructed before we call join() in the base class. So, to make the thread_base safe, we have to do the following: class thread_base : noncopyable { public: ~thread_base() { delete pThread_; } void start() { pThread_ = new boost::thread( *this ); } void join() { pThread_->join(); } private: virtual void operator()() = 0; friend class boost::thread; boost::thread * pThread_; }; And call start() in the subclass constructor and call join() in the subclass destructor, what can be easily forgotten by someone deriving from thread_base. I think this was one of the reasons why the design of boost::thread did not go down this road... Regards, Andreas