00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017 #ifndef __MX_THREAD_H__
00018 #define __MX_THREAD_H__
00019
00020 #include "SDL.h"
00021 #include "SDL_thread.h"
00022
00023 namespace mx
00024 {
00025
00026
00027 int thread_exec(void *data);
00028 int thread_execute(void *data);
00029
00033 class mxMutex {
00034 public:
00036 mxMutex();
00037 ~mxMutex();
00039 int lockMutex();
00041 int unlockMutex();
00042 protected:
00043 SDL_mutex *m;
00044 private:
00045 mxMutex(const mxMutex &);
00046 mxMutex &operator=(const mxMutex &);
00047
00048 };
00049
00053 class mxExec {
00054
00055 public:
00057 mxExec() { }
00058 virtual ~mxExec() { }
00061 virtual int threadExec() = 0;
00062
00063 };
00064
00066 class mxThread : public mxExec {
00067
00068 public:
00070 mxThread();
00071
00072 virtual ~mxThread();
00074 void threadRun();
00075 virtual int threadExec() = 0;
00077 void threadStop();
00079 void threadWait();
00080 protected:
00081 SDL_Thread *thread_identifier;
00082 };
00083
00084
00087 template<typename Class, typename Parameter>
00088 class mxThreadObject : public mxExec {
00089
00090 public:
00091
00093 mxThreadObject(Class *ptr, int (Class::*f)(Parameter p))
00094 {
00095 cls = ptr;
00096 func = f;
00097 thread_identifier = 0;
00098 }
00099
00100 ~mxThreadObject();
00101
00105 void threadRun(Parameter p);
00109 void threadStop();
00111 void threadWait();
00113 virtual int threadExec();
00115 const bool isRunning() const { return running; }
00116 protected:
00117 bool running;
00118 int (Class::*func)(Parameter p);
00119 Class *cls;
00120 SDL_Thread *thread_identifier;
00121 Parameter code_param;
00122
00123 };
00124 template<typename Class, typename Parameter>
00125 mxThreadObject<Class,Parameter>::~mxThreadObject()
00126 {
00127
00128 if(thread_identifier != 0)
00129 SDL_KillThread(thread_identifier);
00130
00131 thread_identifier = 0;
00132 }
00133 template<typename Class, typename Parameter>
00134 void mxThreadObject<Class,Parameter>::threadRun(Parameter p)
00135 {
00136
00137 code_param = p;
00138 running = true;
00139 thread_identifier = SDL_CreateThread(thread_execute, (void*)this);
00140
00141 }
00142 template<typename Class, typename Parameter>
00143 int mxThreadObject<Class,Parameter>::threadExec()
00144 {
00145
00146 if(cls == 0) return 0;
00147
00148
00149 int rt = (*cls.*func)(code_param);
00150 running = false;
00151 return rt;
00152 }
00153 template<typename Class, typename Parameter>
00154 void mxThreadObject<Class,Parameter>::threadWait()
00155 {
00156 if(thread_identifier != 0)
00157 SDL_WaitThread(thread_identifier, 0);
00158 }
00159 template<typename Class, typename Parameter>
00160 void mxThreadObject<Class,Parameter>::threadStop()
00161 {
00162 if(thread_identifier != 0)
00163 SDL_KillThread(thread_identifier);
00164
00165 thread_identifier = 0;
00166 }
00167 }
00168 #endif
00169