00001 00006 00007 00008 #ifndef THREADS_HPP 00009 #define THREADS_HPP 00010 00011 00012 #include "debug.hpp" 00013 00014 00015 typedef void (*AI_ThreadRoutine)(void* opaque); 00016 00017 struct AI_CriticalSectionStruct; 00018 typedef AI_CriticalSectionStruct* AI_CriticalSection; 00019 00020 00021 // threads 00022 bool AI_CreateThread(AI_ThreadRoutine routine, void* opaque, int priority = 0); 00023 00024 // waiting 00025 void AI_Sleep(unsigned milliseconds); 00026 00027 // critical section 00028 AI_CriticalSection AI_CreateCriticalSection(); 00029 void AI_DestroyCriticalSection(AI_CriticalSection cs); 00030 void AI_EnterCriticalSection(AI_CriticalSection cs); 00031 void AI_LeaveCriticalSection(AI_CriticalSection cs); 00032 00033 00034 class Synchronized { 00035 public: 00036 Synchronized() { 00037 m_cs = AI_CreateCriticalSection(); 00038 // if it fails... shit 00039 } 00040 00041 ~Synchronized() { 00042 AI_DestroyCriticalSection(m_cs); 00043 } 00044 00045 void Lock() { 00046 00047 ADR_LOG("--> Trying to lock"); 00048 AI_EnterCriticalSection(m_cs); 00049 ADR_LOG("-->:: LOCKED ::"); 00050 } 00051 00052 void Unlock() { 00053 ADR_LOG("<-- Unlocking..."); 00054 AI_LeaveCriticalSection(m_cs); 00055 } 00056 00057 private: 00058 AI_CriticalSection m_cs; 00059 }; 00060 00061 00062 class AI_Lock { 00063 public: 00064 AI_Lock(Synchronized* object) 00065 : m_object(object) { 00066 object->Lock(); 00067 } 00068 00069 ~AI_Lock() { 00070 m_object->Unlock(); 00071 } 00072 00073 private: 00074 Synchronized* m_object; 00075 }; 00076 00077 00078 #endif