I give a simple and clean design, no signal, no synchronization, no need for killing.
for your MyThread, I suggest renaming and adding as shown below:
class MyThread {
public:
virutal ~MyThread();
virtual bool OnStart() = 0;
virtual bool OnStop() = 0;
virtual int OnRun() = 0;
};
the user of the thread interface will control the lifetime of MyThread.
and actually the real flow object is as follows:
class IThread
{
public:
virtual API ~IThread() {}
virtual void Destroy(void) = 0;
virtual bool Start(void) = 0;
virtual void Stop(void) = 0;
virtual int Wait(void) = 0;
virtual MyThread * Command(void) = 0;
};
extern IThread * ThrdCreate(MyThread *p);
See full interface
http://effoaddon.googlecode.com/svn/trunk/devel/effo/codebase/addons/thrd/include/thrd_i.h
Coding Examples
Case 1. Controlled flow cycle
class ThreadLoop : public MyThread
{
private:
bool m_bRunning;
public:
virtual bool OnStart() { m_bRunning = true; }
virtual bool OnStop() { m_bRunning = false; }
virtual int OnRun()
{
while (m_bRunning) {
do your job;
}
}
};
int main(int argc, char **argv)
{
ThreadLoop oLoop;
IThread *pThread = ThrdCreate(&oLoop);
pThread->Start();
do your things here. when it is time to stop the thread, call stop().
pThread->Stop();
pThread->Destroy();
}
Case 2. I do not know when the flow will stop
class ThreadLoop : public MyThread
{
public:
virtual bool OnStart() { }
virtual bool OnStop() { }
virtual int OnRun()
{
do your job until finish.
}
};
int main(int argc, char **argv)
{
ThreadLoop oLoop;
IThread *pThread = ThrdCreate(&oLoop);
// Start the thread, it will call Loop::OnStart()
//and then call Loop::OnRun() internally.
pThread->Start();
do your things here. Since you don't know when the job will
finish in the thread loop. call wait().
// Wait the thread, it doesn't call Loop::OnStop()
pThread->Wait();
// done, destroy the thread
pThread->Destroy();
}
Full implementation of IThread:
cm
http:
source
share