win_lock.hpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //
  2. // win_lock.cpp
  3. // threadpp
  4. //
  5. // Created by Melo Yao on 1/15/15.
  6. // Copyright (c) 2015 Melo Yao. All rights reserved.
  7. //
  8. #ifndef __threadpp__win_lock__hpp__
  9. #define __threadpp__win_lock__hpp__
  10. #include "win_thread.h"
  11. #include "../threadpp_assert.h"
  12. #include "stdio.h"
  13. namespace threadpp{
  14. static inline void test_error(const char* title)
  15. {
  16. DWORD e = GetLastError();
  17. ASSERT(e==0,"%s failed,error:%d",title,e);
  18. }
  19. inline win_lock::win_lock():_owner(0),_count(0)
  20. {
  21. SetLastError(0);
  22. InitializeCriticalSection(&_mutex);
  23. InitializeConditionVariable(&_cond);
  24. test_error("init");
  25. }
  26. inline win_lock::~win_lock()
  27. {
  28. DeleteCriticalSection(&_mutex);
  29. }
  30. inline void win_lock::lock()
  31. {
  32. SetLastError(0);
  33. EnterCriticalSection(&_mutex);
  34. test_error("lock");
  35. }
  36. inline void win_lock::unlock()
  37. {
  38. SetLastError(0);
  39. LeaveCriticalSection(&_mutex);
  40. test_error("unlock");
  41. }
  42. inline void win_lock::wait()
  43. {
  44. SetLastError(0);
  45. SleepConditionVariableCS(&_cond,&_mutex,0xFFFFFFFF);
  46. test_error("wait");
  47. }
  48. inline void win_lock::wait(unsigned long millisecs)
  49. {
  50. SetLastError(0);
  51. SleepConditionVariableCS(&_cond,&_mutex,millisecs);
  52. DWORD e = GetLastError();
  53. ASSERT(e==0||e == ERROR_TIMEOUT,"timed wait failed,error:",e);
  54. }
  55. inline void win_lock::notify()
  56. {
  57. SetLastError(0);
  58. WakeConditionVariable(&_cond);
  59. test_error("notify");
  60. }
  61. inline void win_lock::notify_all()
  62. {
  63. SetLastError(0);
  64. WakeAllConditionVariable(&_cond);
  65. test_error("notify all");
  66. }
  67. }
  68. #endif