CriticalSection.h
上传用户:liguizhu
上传日期:2015-11-01
资源大小:2422k
文件大小:2k
源码类别:

P2P编程

开发平台:

Visual C++

  1. /*
  2. *  Openmysee
  3. *
  4. *  This program is free software; you can redistribute it and/or modify
  5. *  it under the terms of the GNU General Public License as published by
  6. *  the Free Software Foundation; either version 2 of the License, or
  7. *  (at your option) any later version.
  8. *
  9. *  This program is distributed in the hope that it will be useful,
  10. *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12. *  GNU General Public License for more details.
  13. *
  14. *  You should have received a copy of the GNU General Public License
  15. *  along with this program; if not, write to the Free Software
  16. *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  17. *
  18. */
  19. #ifndef __CRISECTION_H
  20. #define __CRISECTION_H
  21. namespace UC
  22. {
  23. #ifdef WIN32
  24.     
  25. #include <Windows.h>
  26.     
  27. #else
  28.     
  29. #include <pthread.h>
  30. #include <unistd.h>
  31. #endif//_XNIX
  32.     
  33.     
  34.     class CCriticalSection
  35.     {
  36.     private:
  37.         //windows OS
  38. #ifdef WIN32
  39.         CRITICAL_SECTION moSection;
  40. #else
  41.         pthread_mutex_t mMutex;
  42. #endif
  43.         
  44.         
  45.     public:
  46.         CCriticalSection()
  47.         {
  48. #ifdef WIN32
  49.             InitializeCriticalSection(&moSection);
  50. #else
  51.             mMutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
  52.             //pthread_mutex_init(&mMutex,NULL);
  53. #endif
  54.         };
  55.         ~CCriticalSection()
  56.         {
  57. #ifdef WIN32
  58.             DeleteCriticalSection(&moSection);
  59. #else
  60.             pthread_mutex_destory(&mMutex);
  61. #endif
  62.         }
  63.         void  inline Enter()
  64.         {
  65. #ifdef WIN32
  66.             EnterCriticalSection(&moSection);
  67. #else
  68.             pthread_mutex_lock(&mMutex);
  69. #endif
  70.         }
  71.         void inline Leave()
  72.         {
  73. #ifdef WIN32
  74.             LeaveCriticalSection(&moSection);
  75. #else
  76.             pthread_mutex_unlock(&mMutex);
  77. #endif
  78.         };
  79.         
  80.     };
  81.     class CCriticalSectionHelper
  82.     {
  83.     public:
  84.         CCriticalSectionHelper(CCriticalSection& aCriticalSection)
  85.             :moCriticalSection(aCriticalSection)
  86.         {
  87.             moCriticalSection.Enter();
  88.         };
  89.         ~CCriticalSectionHelper(){
  90.             moCriticalSection.Leave();
  91.         }
  92.     private:
  93.         CCriticalSection& moCriticalSection;
  94.     };
  95. };
  96. #endif // __CRISECTION_H