Re: C++ Thread Class
red floyd wrote:
alex wrote:
jayesah@gmail.com wrote:
I am writting a Thread class with using pthread library. I have some
problem in saving thread function type and argument type. How to make
Thread class generic ?
Have you considered inheritance?
class Thread
{
public:
void start(void);
virtual void run(void) = 0;
};
class MyThread
: public Thread
{
public:
virtual void run(void);
};
Better would be:
class Thread
{
public:
static void start(void *param)
{
static_cast<Thread*>(param)->run();
}
private:
virtual void run() = 0;
protected:
virtual ~Thread() {}
};
Why?
In general, there are two ways to attain genericity in C++,
inheritance and templates. Inheritance allows runtime
genericity, and is thus more flexible. On the other hand, it
requires reference semantics in order to work. Templates must
be resolved at compile time, but allow copy semantics. In this
particular case, I can't really think of a good use for the
added flexibility of run-time genericity, and you definitly want
copy semantics, if at all possible, to limit the risk of
multiple threads accessing the same data, so the choice is
obvious. Boost::threads handles this aspect particularly well.
(One thing I'm not sure of, however: can the functional object
used by a boost::thread contain e.g. an std::auto_ptr, or do
they impose the same Copiable/Assignable constraints that STL
containers do? Because passing data between threads is one
place where std::auto_ptr really shines.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]