00001
00002
00003
00004
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 #include "precomp.h"
00030 #include "thread.h"
00031 #include "runnable.h"
00032
00034
00035
00036 CL_Thread::CL_Thread() : handle(0)
00037 {
00038 }
00039
00040 CL_Thread::~CL_Thread()
00041 {
00042 #ifdef WIN32
00043 if (handle)
00044 CloseHandle(handle);
00045 #else
00046
00047
00048 if (handle)
00049 pthread_cancel(handle);
00050 #endif
00051 }
00052
00054
00055
00057
00058
00059 void CL_Thread::start(CL_Runnable *runnable)
00060 {
00061 if (runnable == 0)
00062 throw CL_Exception(TEXT("Invalid runnable pointer"));
00063
00064 #ifdef WIN32
00065 if (handle)
00066 CloseHandle(handle);
00067
00068 DWORD threadId = 0;
00069 handle = CreateThread(0, 0, &CL_Thread::thread_main, runnable, 0, &threadId);
00070 if (handle == 0)
00071 {
00072 throw CL_Exception(TEXT("Unable to create new thread"));
00073 }
00074 #else
00075 int result = pthread_create(&handle, 0, thread_main, runnable);
00076 if (result != 0)
00077 {
00078 handle = 0;
00079 throw CL_Exception(TEXT("Unable to create new thread"));
00080 }
00081 #endif
00082 }
00083
00084 void CL_Thread::join()
00085 {
00086 #ifdef WIN32
00087 WaitForSingleObject(handle, INFINITE);
00088 if (handle)
00089 CloseHandle(handle);
00090 #else
00091 pthread_join(handle, 0);
00092 #endif
00093 handle = 0;
00094 }
00095
00097
00098
00099 #ifdef WIN32
00100 DWORD CL_Thread::thread_main(void *data)
00101 {
00102 CL_Runnable *runnable = (CL_Runnable *) data;
00103 runnable->run();
00104 return 0;
00105 }
00106 #else
00107 void *CL_Thread::thread_main(void *data)
00108 {
00109
00110 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
00111
00112 CL_Runnable *runnable = (CL_Runnable *) data;
00113 runnable->run();
00114 return 0;
00115 }
00116 #endif