1 #ifndef _WIN32 2 #include "threads.h" 3 #include <cstdlib> 4 #include <unistd.h> 5 #include <pthread.h> 6 7 extern "C" { startfunc(void * arg)8static void* startfunc(void *arg) 9 { 10 Thread *thr = reinterpret_cast<Thread *>(arg); 11 thr->doRun(); 12 return NULL; 13 } 14 } 15 Thread(StartFunc startfn,void * arg)16Thread::Thread(StartFunc startfn, void *arg) 17 { 18 this->fn = startfn; 19 this->fnparam = arg; 20 initialized = true; 21 pthread_create(&thr, NULL, startfunc, this); 22 } 23 24 void close()25Thread::close() 26 { 27 if (!initialized) { 28 return; 29 } 30 join(); 31 initialized = false; 32 } 33 ~Thread()34Thread::~Thread() 35 { 36 close(); 37 } 38 39 void join()40Thread::join() 41 { 42 void *res; 43 pthread_join(thr, &res); 44 } 45 46 47 // Mutex: Mutex()48Mutex::Mutex() 49 { 50 pthread_mutex_init(&mutex, NULL); 51 initialized = true; 52 } 53 54 void lock()55Mutex::lock() 56 { 57 pthread_mutex_lock(&mutex); 58 } 59 60 bool tryLock()61Mutex::tryLock() 62 { 63 return pthread_mutex_trylock(&mutex) == 0; 64 } 65 66 void unlock()67Mutex::unlock() 68 { 69 pthread_mutex_unlock(&mutex); 70 } 71 72 void close()73Mutex::close() 74 { 75 if (initialized) { 76 initialized = false; 77 pthread_mutex_destroy(&mutex); 78 } 79 } 80 ~Mutex()81Mutex::~Mutex() 82 { 83 close(); 84 } 85 86 87 // Condvar Condvar()88Condvar::Condvar() 89 { 90 pthread_cond_init(&cond, NULL); 91 initialized = true; 92 } 93 94 void wait(Mutex & mutex)95Condvar::wait(Mutex& mutex) 96 { 97 pthread_cond_wait(&cond, &mutex.mutex); 98 } 99 100 void signal()101Condvar::signal() 102 { 103 pthread_cond_signal(&cond); 104 } 105 106 void close()107Condvar::close() 108 { 109 if (initialized) { 110 pthread_cond_destroy(&cond); 111 initialized = false; 112 } 113 } 114 ~Condvar()115Condvar::~Condvar() 116 { 117 close(); 118 } 119 #endif 120