00001 #ifndef _sys_Thread_h
00002 #define _sys_Thread_h
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025 #include "Runnable.h"
00026
00027 #ifdef USE_APR
00028 #include <apr_thread_proc.h>
00029 #include <apr_portable.h>
00030 #include "apr/APRPool.h"
00031 #include "apr/APRBase.h"
00032 #else
00033 #include "posix/check.h"
00034 #include <pthread.h>
00035 #endif
00036
00037 namespace qpid {
00038 namespace sys {
00039
00040 class Thread
00041 {
00042 public:
00043 inline static Thread current();
00044 inline static void yield();
00045
00046 inline Thread();
00047 inline explicit Thread(qpid::sys::Runnable*);
00048 inline explicit Thread(qpid::sys::Runnable&);
00049
00050 inline void join();
00051
00052 inline long id();
00053
00054 private:
00055 #ifdef USE_APR
00056 static void* APR_THREAD_FUNC runRunnable(apr_thread_t* thread, void *data);
00057 inline Thread(apr_thread_t* t);
00058 apr_thread_t* thread;
00059 #else
00060 static void* runRunnable(void* runnable);
00061 inline Thread(pthread_t);
00062 pthread_t thread;
00063 #endif
00064 };
00065
00066
00067 Thread::Thread() : thread(0) {}
00068
00069
00070 #ifdef USE_APR
00071
00072 Thread::Thread(Runnable* runnable) {
00073 CHECK_APR_SUCCESS(
00074 apr_thread_create(&thread, 0, runRunnable, runnable, APRPool::get()));
00075 }
00076
00077 Thread::Thread(Runnable& runnable) {
00078 CHECK_APR_SUCCESS(
00079 apr_thread_create(&thread, 0, runRunnable, &runnable, APRPool::get()));
00080 }
00081
00082 void Thread::join(){
00083 apr_status_t status;
00084 if (thread != 0)
00085 CHECK_APR_SUCCESS(apr_thread_join(&status, thread));
00086 }
00087
00088 long Thread::id() {
00089 return long(thread);
00090 }
00091
00092 Thread::Thread(apr_thread_t* t) : thread(t) {}
00093
00094 Thread Thread::current(){
00095 apr_thread_t* thr;
00096 apr_os_thread_t osthr = apr_os_thread_current();
00097 CHECK_APR_SUCCESS(apr_os_thread_put(&thr, &osthr, APRPool::get()));
00098 return Thread(thr);
00099 }
00100
00101 void Thread::yield()
00102 {
00103 apr_thread_yield();
00104 }
00105
00106
00107
00108 #else
00109
00110 Thread::Thread(Runnable* runnable) {
00111 QPID_POSIX_THROW_IF(pthread_create(&thread, NULL, runRunnable, runnable));
00112 }
00113
00114 Thread::Thread(Runnable& runnable) {
00115 QPID_POSIX_THROW_IF(pthread_create(&thread, NULL, runRunnable, &runnable));
00116 }
00117
00118 void Thread::join(){
00119 QPID_POSIX_THROW_IF(pthread_join(thread, 0));
00120 }
00121
00122 long Thread::id() {
00123 return long(thread);
00124 }
00125
00126 Thread::Thread(pthread_t thr) : thread(thr) {}
00127
00128 Thread Thread::current() {
00129 return Thread(pthread_self());
00130 }
00131
00132 void Thread::yield()
00133 {
00134 QPID_POSIX_THROW_IF(pthread_yield());
00135 }
00136
00137
00138 #endif
00139
00140 }}
00141
00142 #endif