KMutex.cpp
上传用户:dzyhzl
上传日期:2019-04-29
资源大小:56270k
文件大小:2k
源码类别:

模拟服务器

开发平台:

C/C++

  1. //---------------------------------------------------------------------------
  2. // Sword3 Engine (c) 1999-2000 by Kingsoft
  3. //
  4. // File: KMutex.cpp
  5. // Date: 2000.08.08
  6. // Code: WangWei(Daphnis)
  7. // Desc: Implements a simple mutex object for thread synchronization
  8. //---------------------------------------------------------------------------
  9. #include "KWin32.h"
  10. #include "KDebug.h"
  11. #include "KMutex.h"
  12. KMutex::KMutex()
  13. {
  14. #ifdef WIN32
  15. #ifdef SINGLE_PROCESS
  16. InitializeCriticalSection(&m_CriticalSection);
  17. #else
  18. m_hMutex = CreateMutex(NULL, FALSE, NULL);
  19. if (!m_hMutex)
  20. g_MessageBox("KMutex::KMutex() CreateMutex() failed!");
  21. #endif
  22. #else
  23.      int rc = pthread_mutex_init(&mutex, NULL);
  24. #endif
  25. }
  26. //---------------------------------------------------------------------------
  27. // 函数: ~KMutex
  28. // 功能: 析购函数
  29. // 参数: void
  30. // 返回: void
  31. //---------------------------------------------------------------------------
  32. KMutex::~KMutex()
  33. {
  34. #ifdef WIN32
  35. #ifdef SINGLE_PROCESS
  36. DeleteCriticalSection(&m_CriticalSection);
  37. #else
  38. CloseHandle(m_hMutex);
  39. #endif
  40. #else
  41.      int rc = pthread_mutex_destroy(&mutex);
  42.      printf("create mutex%dn", rc);
  43. #endif
  44. }
  45. //---------------------------------------------------------------------------
  46. // 函数: Lock
  47. // 功能: 锁定
  48. // 参数: void
  49. // 返回: void
  50. //---------------------------------------------------------------------------
  51. void KMutex::Lock(void)
  52. {
  53. #ifdef WIN32
  54. #ifdef SINGLE_PROCESS
  55. EnterCriticalSection(&m_CriticalSection);
  56. #else
  57. WaitForSingleObject(m_hMutex, INFINITE);
  58. #endif
  59. #else
  60.      int rc = pthread_mutex_lock(&mutex);
  61. #endif
  62. }
  63. //---------------------------------------------------------------------------
  64. // 函数: Unlock
  65. // 功能: 解开
  66. // 参数: void
  67. // 返回: void
  68. //---------------------------------------------------------------------------
  69. void KMutex::Unlock(void)
  70. {
  71. #ifdef WIN32
  72. #ifdef SINGLE_PROCESS
  73. LeaveCriticalSection(&m_CriticalSection);
  74. #else
  75. ReleaseMutex(m_hMutex);
  76. #endif
  77. #else
  78.      int rc = pthread_mutex_unlock(&mutex);
  79. #endif
  80. }