00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020 #include "Thread.h"
00021 #include "Runnable.h"
00022 #include "ThreadManager.h"
00023
00024 namespace mdw
00025 {
00026 void* Thread::staticStart (void *arg)
00027 {
00028 Thread *thread = (Thread*) arg;
00029 thread->internalStart();
00030 }
00031
00032 Thread::Thread (Runnable &runnable) : _runnable (runnable)
00033 {
00034 ThreadManager &tm = ThreadManager::getInstance();
00035 tm.registerThread (*this);
00036 }
00037 Thread::~Thread()
00038 {
00039 ThreadManager &tm = ThreadManager::getInstance();
00040 tm.unregisterThread (*this);
00041 }
00042
00043 bool Thread::run()
00044 {
00045 return _runnable.run();
00046 }
00047 void Thread::start (bool joinable)
00048 {
00049 _started = true;
00050 ThreadStatic::thread_attr_t attribute;
00051 ThreadStatic::thread_attr_init (attribute);
00052 if (joinable)
00053 {
00054 ThreadStatic::setdetachstate (attribute, ThreadStatic::Joinable_e);
00055 }
00056 else
00057 {
00058 ThreadStatic::setdetachstate (attribute, ThreadStatic::Detached_e);
00059 }
00060 ThreadStatic::create (_threadId, &staticStart, this, attribute);
00061 ThreadStatic::thread_attr_destroy (attribute);
00062 }
00063
00064 void Thread::stop()
00065 {
00066 _started = false;
00067 }
00068 void Thread::kill()
00069 {
00070 ThreadStatic::cancel (_threadId);
00071 }
00072 void Thread::join()
00073 {
00074 void ** res;
00075 ThreadStatic::join (_threadId, res);
00076 }
00077
00078 void Thread::internalStart()
00079 {
00080 while (_started)
00081 {
00082 _runnable.run();
00083 }
00084 }
00085
00086 }