summary |
shortlog |
log |
commit | commitdiff |
tree
raw |
patch |
inline | side by side (from parent 1:
89c8388)
Trying to re-launch a thread after it has finished now throws a
logic_error.
Added a state to indicate the thread having finished.
#include <pthread.h>
#include <signal.h>
#endif
#include <pthread.h>
#include <signal.h>
#endif
namespace Msp {
struct Thread::Private
namespace Msp {
struct Thread::Private
Private(): handle(0) { }
#ifdef WIN32
Private(): handle(0) { }
#ifdef WIN32
- static DWORD WINAPI main_wrapper(void *t)
- { reinterpret_cast<Thread *>(t)->main(); return 0; }
- static void *main_wrapper(void *t)
- { reinterpret_cast<Thread *>(t)->main(); return 0; }
+ main_wrapper(void *a)
+ {
+ Thread *t = reinterpret_cast<Thread *>(a);
+ t->main();
+ t->state_ = FINISHED;
+ return 0;
+ }
};
Thread::Thread():
priv_(new Private),
};
Thread::Thread():
priv_(new Private),
- if(launched_)
- {
- kill();
- join();
- }
delete priv_;
}
void Thread::join()
{
delete priv_;
}
void Thread::join()
{
#else
pthread_join(priv_->handle, 0);
#endif
#else
pthread_join(priv_->handle, 0);
#endif
+ if(state_!=RUNNING)
+ return;
+
#ifdef WIN32
TerminateThread(priv_->handle, 0);
#else
pthread_kill(priv_->handle, SIGKILL);
#endif
#ifdef WIN32
TerminateThread(priv_->handle, 0);
#else
pthread_kill(priv_->handle, SIGKILL);
#endif
}
void Thread::launch()
{
}
void Thread::launch()
{
- if(launched_)
- return;
+ if(state_>=RUNNING)
+ throw logic_error("already launched");
#ifdef WIN32
DWORD dummy; // Win9x needs the lpTthreadId parameter
#ifdef WIN32
DWORD dummy; // Win9x needs the lpTthreadId parameter
#else
pthread_create(&priv_->handle, 0, &Private::main_wrapper, this);
#endif
#else
pthread_create(&priv_->handle, 0, &Private::main_wrapper, this);
#endif
+ enum State
+ {
+ PENDING,
+ RUNNING,
+ FINISHED,
+ KILLED,
+ JOINED
+ };
+
public:
virtual ~Thread();
public:
virtual ~Thread();
+ /** Indicates whether the thread has finished running. */
+ bool is_finished() { return state_>=FINISHED; }
+
/** Waits for the thread to exit. Calling this from the thread will cause a
deadlock. */
void join();
/** Waits for the thread to exit. Calling this from the thread will cause a
deadlock. */
void join();
/** Violently terminates the thread. This should only be used as a last
resort, as the thread gets no chance to clean up. */
void kill();
/** Violently terminates the thread. This should only be used as a last
resort, as the thread gets no chance to clean up. */
void kill();
+ /** Starts the thread. Can only be called once for each Thread instance. */
virtual void main() = 0;
};
virtual void main() = 0;
};