00001 // this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*- 00002 //---------------------------------------------------------------------- 00009 //---------------------------------------------------------------------- 00010 #include "Thread.h" 00011 00012 #include <icl_core/os_time.h> 00013 00014 #if defined _SYSTEM_LXRT_ 00015 # include "ThreadImplLxrt.h" 00016 #endif 00017 00018 #if defined _SYSTEM_POSIX_ 00019 # include "ThreadImplPosix.h" 00020 #elif defined _SYSTEM_WIN32_ 00021 # include "ThreadImplWin32.h" 00022 #else 00023 # error "No thread implementation defined for this platform." 00024 #endif 00025 00026 namespace icl_core { 00027 namespace logging { 00028 00029 Thread::Thread(icl_core::ThreadPriority priority) 00030 : m_execute(false), 00031 m_finished(true), 00032 m_joined(true), 00033 m_starting(false), 00034 m_impl(0) 00035 { 00036 #if defined _SYSTEM_LXRT_ 00037 // Only create an LXRT implementation if the LXRT runtime system 00038 // is really available. Otherwise create an ACE or POSIX implementation, 00039 // depending on the system configuration. 00040 // Remark: This allows us to compile programs with LXRT support but run 00041 // them on systems on which no LXRT is installed and to disable LXRT support 00042 // at program startup on systems with installed LXRT! 00043 if (icl_core::os::isThisLxrtTask()) 00044 { 00045 m_impl = new ThreadImplLxrt(this, priority); 00046 } 00047 else 00048 { 00049 m_impl = new ThreadImplPosix(this, priority); 00050 } 00051 00052 #elif defined _SYSTEM_POSIX_ 00053 m_impl = new ThreadImplPosix(this, priority); 00054 00055 #elif defined _SYSTEM_WIN32_ 00056 m_impl = new ThreadImplWin32(this, priority); 00057 00058 #endif 00059 } 00060 00061 Thread::~Thread() 00062 { 00063 if (!m_joined) 00064 { 00065 stop(); 00066 join(); 00067 } 00068 delete m_impl; 00069 } 00070 00071 void Thread::join() 00072 { 00073 if (running()) 00074 { 00075 m_impl->join(); 00076 } 00077 00078 m_joined = true; 00079 } 00080 00081 bool Thread::start() 00082 { 00083 // Don't do anything if the thread is already starting or running. 00084 if (m_starting || running()) 00085 { 00086 waitStarted(); 00087 00088 return running(); 00089 } 00090 00091 m_starting = true; 00092 m_finished = false; 00093 00094 if (!m_joined) 00095 { 00096 join(); 00097 } 00098 00099 m_joined = false; 00100 00101 if (!m_impl->start()) 00102 { 00103 m_finished = true; 00104 m_starting = false; 00105 m_joined = true; 00106 00107 return false; 00108 } 00109 else 00110 { 00111 waitStarted(); 00112 00113 return true; 00114 } 00115 } 00116 00117 void Thread::runThread() 00118 { 00119 m_execute = true; 00120 m_starting = false; 00121 m_finished = false; 00122 00123 run(); 00124 00125 m_execute = false; 00126 m_finished = true; 00127 } 00128 00129 void Thread::waitStarted() const 00130 { 00131 while (m_starting) 00132 { 00133 // Sleep for 1 microsecond. 00134 icl_core::os::usleep(1); 00135 } 00136 } 00137 00138 } 00139 }