00001
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030 #include <stdio.h>
00031 #ifdef _WIN32
00032 #include <process.h>
00033 #include "socket_include.h"
00034 #else
00035 #include <unistd.h>
00036 #endif
00037
00038 #include "Thread.h"
00039
00040
00041 #ifdef SOCKETS_NAMESPACE
00042 namespace SOCKETS_NAMESPACE {
00043 #endif
00044
00045
00046 Thread::Thread(bool release)
00047 :m_thread(0)
00048 ,m_running(true)
00049 ,m_release(false)
00050 ,m_b_delete_on_exit(false)
00051 ,m_b_destructor(false)
00052 {
00053 #ifdef _WIN32
00054
00055 m_thread = (HANDLE)_beginthreadex(NULL, 0, &StartThread, this, 0, &m_dwThreadId);
00056 #else
00057 pthread_attr_t attr;
00058
00059 pthread_attr_init(&attr);
00060 pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
00061 if (pthread_create(&m_thread,&attr, StartThread,this) == -1)
00062 {
00063 perror("Thread: create failed");
00064 SetRunning(false);
00065 }
00066
00067 #endif
00068 m_release = release;
00069 }
00070
00071
00072 Thread::~Thread()
00073 {
00074 m_b_destructor = true;
00075 if (m_running)
00076 {
00077 SetRelease(true);
00078 SetRunning(false);
00079 #ifdef _WIN32
00080 Sleep(1000);
00081 #else
00082 sleep(1);
00083 #endif
00084 }
00085 #ifdef _WIN32
00086 if (m_thread)
00087 ::CloseHandle(m_thread);
00088 #endif
00089 }
00090
00091
00092 threadfunc_t STDPREFIX Thread::StartThread(threadparam_t zz)
00093 {
00094 Thread *p = (Thread *)zz;
00095
00096 while (p -> m_running && !p -> m_release)
00097 {
00098 #ifdef _WIN32
00099 Sleep(1000);
00100 #else
00101 sleep(1);
00102 #endif
00103 }
00104 if (p -> m_running)
00105 {
00106 p -> Run();
00107 }
00108 p -> SetRunning(false);
00109 if (p -> DeleteOnExit() && !p -> IsDestructor())
00110 {
00111 delete p;
00112 }
00113 #ifdef _WIN32
00114 _endthreadex(0);
00115 #endif
00116 return (threadfunc_t)NULL;
00117 }
00118
00119
00120 bool Thread::IsRunning()
00121 {
00122 return m_running;
00123 }
00124
00125
00126 void Thread::SetRunning(bool x)
00127 {
00128 m_running = x;
00129 }
00130
00131
00132 bool Thread::IsReleased()
00133 {
00134 return m_release;
00135 }
00136
00137
00138 void Thread::SetRelease(bool x)
00139 {
00140 m_release = x;
00141 }
00142
00143
00144 bool Thread::DeleteOnExit()
00145 {
00146 return m_b_delete_on_exit;
00147 }
00148
00149
00150 void Thread::SetDeleteOnExit(bool x)
00151 {
00152 m_b_delete_on_exit = x;
00153 }
00154
00155
00156 bool Thread::IsDestructor()
00157 {
00158 return m_b_destructor;
00159 }
00160
00161
00162 #ifdef SOCKETS_NAMESPACE
00163 }
00164 #endif
00165