random_utils/include/random_utils/ThreadSafeObject.h

Go to the documentation of this file.
00001 #ifndef _RU_THREADSAFEOBJECT_H_
00002 #define _RU_THREADSAFEOBJECT_H_
00003 
00004 #include <SDL_thread.h>
00005 #include <iostream>
00006 
00010 namespace random_utils
00011 {
00012 
00017 class ThreadSafeObject
00018 {
00022     SDL_mutex*  m_mutexMutex;
00023     
00027     SDL_mutex*  m_syncMutex;
00028 
00033     unsigned int m_lockCount;
00034 
00035 public:
00039     ThreadSafeObject();
00040 
00044     virtual ~ThreadSafeObject();
00045 
00049     inline int lock()
00050     {
00051         int sdlReturnValue = SDL_LockMutex(m_syncMutex);
00052 
00053         if(SDL_LockMutex(m_mutexMutex) == -1)
00054             std::cerr << "ERROR: cannot lock mutex protection" << std::endl;
00055 
00056         if(sdlReturnValue == -1)
00057             std::cerr << "ERROR: cannot lock mutex " 
00058                     << m_syncMutex << std::endl;
00059 
00060         m_lockCount++;
00061         
00062         if(SDL_UnlockMutex(m_mutexMutex) == -1)
00063             std::cerr << "ERROR: cannot unlock mutex protection" << std::endl;
00064         
00065         return sdlReturnValue;
00066     }
00067 
00071     inline int unlock()
00072     {
00073         if(SDL_LockMutex(m_mutexMutex) == -1)
00074             std::cerr << "ERROR: cannot lock mutex protection" << std::endl;
00075 
00076         if(--m_lockCount == 0)
00077         {
00078             if(SDL_UnlockMutex(m_mutexMutex) == -1)
00079                 std::cerr << "ERROR: cannot unlock mutex protection" 
00080                         << std::endl;
00081 
00082             int sdlReturnValue = SDL_UnlockMutex(m_syncMutex);
00083 
00084             if(sdlReturnValue == -1)
00085                 std::cerr << "ERROR: cannot unlock mutex " 
00086                         << m_syncMutex << std::endl;
00087 
00088             return sdlReturnValue;
00089         }
00090         else
00091         {
00092             if(SDL_UnlockMutex(m_mutexMutex) == -1)
00093                 std::cerr << "ERROR: cannot unlock mutex protection" 
00094                         << std::endl;
00095 
00096             return 0;
00097         }
00098     }
00099 
00103     inline bool isLocked()
00104     {
00105         return m_lockCount != 0;
00106     }
00107 
00111     inline SDL_mutex* mutex()
00112     {
00113         return m_syncMutex;
00114     }
00115 
00120     inline unsigned int lockCount()
00121     {
00122         return m_lockCount;
00123     }
00124 };
00125 
00126 } // namespace random_utils
00127 
00128 
00129 #endif // _RU_THREADSAFEOBJECT_H_

Generated on Fri May 11 21:01:58 2007 for Random Racer by  doxygen 1.5.1