Semaphore.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright: JessMA Open Source (ldcsaa@gmail.com)
  3. *
  4. * Version : 2.3.15
  5. * Author : Bruce Liang
  6. * Website : http://www.jessma.org
  7. * Project : https://github.com/ldcsaa
  8. * Blog : http://www.cnblogs.com/ldcsaa
  9. * Wiki : http://www.oschina.net/p/hp-socket
  10. * QQ Group : 75375912
  11. *
  12. * Licensed under the Apache License, Version 2.0 (the "License");
  13. * you may not use this file except in compliance with the License.
  14. * You may obtain a copy of the License at
  15. *
  16. * http://www.apache.org/licenses/LICENSE-2.0
  17. *
  18. * Unless required by applicable law or agreed to in writing, software
  19. * distributed under the License is distributed on an "AS IS" BASIS,
  20. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. * See the License for the specific language governing permissions and
  22. * limitations under the License.
  23. */
  24. #pragma once
  25. class CSEM
  26. {
  27. public:
  28. CSEM(LONG lMaximumCount, LONG lInitialCount = 0, LPCTSTR lpName = nullptr, LPSECURITY_ATTRIBUTES pSecurity = nullptr)
  29. {
  30. m_hsem = ::CreateSemaphore(pSecurity, lInitialCount, lMaximumCount, lpName);
  31. ASSERT(IsValid());
  32. }
  33. ~CSEM()
  34. {
  35. if(IsValid())
  36. VERIFY(::CloseHandle(m_hsem));
  37. }
  38. BOOL Open(DWORD dwAccess, BOOL bInheritHandle, LPCTSTR pszName)
  39. {
  40. if(IsValid())
  41. VERIFY(::CloseHandle(m_hsem));
  42. m_hsem = ::OpenSemaphore(dwAccess, bInheritHandle, pszName);
  43. return(IsValid());
  44. }
  45. void Wait(DWORD dwMilliseconds = INFINITE)
  46. {
  47. ::WaitForSingleObject(m_hsem, dwMilliseconds);
  48. }
  49. BOOL Release(LONG lReleaseCount = 1, LPLONG lpPreviousCount = nullptr)
  50. {
  51. return ::ReleaseSemaphore(m_hsem, lReleaseCount, lpPreviousCount);
  52. }
  53. HANDLE& GetHandle () {return m_hsem;}
  54. operator HANDLE () {return m_hsem;}
  55. BOOL IsValid () {return m_hsem != nullptr;}
  56. private:
  57. CSEM(const CSEM& sem);
  58. CSEM operator = (const CSEM& sem);
  59. private:
  60. HANDLE m_hsem;
  61. };