00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017 #ifndef AMINO_UTIL_THREAD
00018 #define AMINO_UTIL_THREAD
00019
00020 #include <pthread.h>
00021 #include <string>
00022 #include <vector>
00023 #include <stdio.h>
00024
00025 namespace amino {
00026 using namespace std;
00027
00038 class Runnable {
00039 public:
00040 virtual void* run() = 0;
00041 virtual ~Runnable() {}
00042 };
00043
00057 class Thread : public Runnable {
00058 private:
00059 bool started;
00060 public:
00061 typedef pthread_t native_handler_type;
00062 Thread() :
00063 runner(NULL) {
00064 threadId = 0;
00065 }
00066
00067 Thread(int id) :
00068 threadId(id), runner(NULL) {
00069 }
00070
00075 Thread(string n, Runnable *r = NULL) :
00076 name(n), runner(r) {
00077 started = false;
00078 }
00079
00086 Thread(Runnable* r) :
00087 runner(r) {
00088 started = false;
00089 }
00090
00096 template <class F> static void * callFuncObj(void * ob) {
00097
00098 (*((F*) (ob)))();
00099 return NULL;
00100 }
00101
00109 template <class F> explicit Thread(F& f) {
00110 pthread_create(&tid, NULL, &callFuncObj<F>, &f);
00111 started = true;
00112 }
00113
00118 virtual void* run() {
00119 printf("Thread::run()\n");
00120 return NULL;
00121 }
00122
00129 void setRunner(Runnable *r) {
00130 this->runner = r;
00131 }
00132
00139 void start() {
00140 pthread_create(&tid, NULL, Thread::execute, this);
00141 }
00142
00147 native_handler_type native_handle() {
00148 return tid;
00149 }
00150
00154 void setName(string name) {
00155 this->name = name;
00156 }
00157
00161 string getName() {
00162 return name;
00163 }
00164
00168 void join() {
00169 pthread_join(tid, NULL);
00170 }
00171
00176 bool joinable() const {
00177 return true;
00178 }
00179
00183 void detach() {
00184 pthread_detach(tid);
00185 }
00186
00187 virtual ~Thread() {
00188
00189
00190 }
00191
00192 private:
00197 static void* execute(void* arg) {
00198 Thread* thread = (Thread*)arg;
00199 if (thread->runner != NULL) {
00200 return thread->runner->run();
00201 } else {
00202 return thread->run();
00203 }
00204 }
00205
00206 protected:
00207 int threadId;
00208 pthread_t tid;
00209 string name;
00210 private:
00211 Runnable* runner;
00212 };
00213 }
00214 #endif