Re: What's the connection between objects and threads?
On May 22, 1:55 am, "Chris Thomasson" <cris...@comcast.net> wrote:
"darren" <minof...@gmail.com> wrote in message
news:7083eb1a-4dbd-4b94-866b-fddab7300186@c19g2000prf.googlegroups.com...
Hi
I have to write a multi-threaded program. I decided to take an OO
approach to it. I had the idea to wrap up all of the thread functions=
in a mix-in class called Threadable. Then when an object should run
in its own thread, it should implement this mix-in class. Does thi=
s
sound like plausible design decision?
I'm surprised that C++ doesn't have such functionality, say in its
STL. This absence of a thread/object relationship in C++ leads me to
believe that my idea isn't a very good one.
I would appreciate your insights. thanks
Here is a helper object you can use to run objects that provide a specific=
interface (e.g., foo::start/join):
_________________________________________________________________
template<typename T>
struct active {
class guard {
T& m_object;
public:
guard(T& object) : m_object(object) {
m_object.start();
}
~guard() {
m_object.join();
}
};
T m_object;
active() {
m_object.start();
}
~active() {
m_object.join();
}};
_________________________________________________________________
To create and start an object in one step you do:
{
active<foo> _foo;
}
or you can separate the process and intervene in between the object
construction and activation like:
{
foo _foo;
[...];
active<foo>::guard active_foo(_foo);
}
However, other than perhaps some syntactic-sugar, I don't think that this
gives any advantages over Boost's method of representing and creating
threads...
Any thoughts?
I do think it has advantages over Boost's method. One such advantage
is the RAII nature of it.
Furthermore, I think it should be taken in into the C++0x standard on
the similar grounds as they provide higher level condition variable
wait API as well:
<quote>
template <class Predicate>
void wait(unique_lock<mutex>& lock, Predicate pred);
Effects:
As if:
while (!pred())
wait(lock);
</quote>
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2497.html
However, one further improvement could be nice, and in that case it
would be quite a general solution, if one could just denote which
method of the object one wants to start as a process.
Best Regards,
Szabolcs