00001 #include <unistd.h> 00002 #include <pthread.h> 00003 #include "threads.hpp" 00004 00005 00006 struct ThreadInternal 00007 { 00008 AI_ThreadRoutine routine; 00009 void* opaque; 00010 }; 00011 00012 00013 struct AI_CriticalSectionStruct 00014 { 00015 pthread_mutex_t mutex; 00016 }; 00017 00018 00020 00021 void* ThreadRoutine(void* arg) 00022 { 00023 ThreadInternal* ti = (ThreadInternal*)arg; 00024 ti->routine(ti->opaque); 00025 delete ti; 00026 return NULL; 00027 } 00028 00030 00031 bool AI_CreateThread(AI_ThreadRoutine routine, void* opaque, int priority) 00032 { 00033 ThreadInternal* ti = new ThreadInternal; 00034 ti->routine = routine; 00035 ti->opaque = opaque; 00036 00037 pthread_t thread; 00038 int result = pthread_create(&thread, NULL, ThreadRoutine, ti); 00039 if (result != 0) { 00040 delete ti; 00041 return false; 00042 } else { 00043 return true; 00044 } 00045 } 00046 00048 00049 void AI_Sleep(unsigned milliseconds) 00050 { 00051 int seconds = milliseconds / 1000; 00052 int useconds = (milliseconds % 1000) * 1000; 00053 00054 sleep(seconds); 00055 usleep(useconds); 00056 } 00057 00059 00060 AI_CriticalSection AI_CreateCriticalSection() 00061 { 00062 AI_CriticalSectionStruct* cs = new AI_CriticalSectionStruct; 00063 int result = pthread_mutex_init(&cs->mutex, NULL); 00064 if (result != 0) { 00065 delete cs; 00066 return NULL; 00067 } 00068 00069 return cs; 00070 } 00071 00073 00074 void AI_DestroyCriticalSection(AI_CriticalSection cs) 00075 { 00076 pthread_mutex_destroy(&cs->mutex); 00077 } 00078 00080 00081 void AI_EnterCriticalSection(AI_CriticalSection cs) 00082 { 00083 pthread_mutex_lock(&cs->mutex); 00084 } 00085 00087 00088 void AI_LeaveCriticalSection(AI_CriticalSection cs) 00089 { 00090 pthread_mutex_unlock(&cs->mutex); 00091 } 00092