lean cpp library
A lean C++ library providing efficient utility classes for high-performance C++ applications.
semaphore.h
00001 /*****************************************************/
00002 /* lean Concurrent              (c) Tobias Zirr 2011 */
00003 /*****************************************************/
00004 
00005 #ifndef LEAN_CONCURRENT_SEMAPHORE
00006 #define LEAN_CONCURRENT_SEMAPHORE
00007 
00008 #include "../lean.h"
00009 #include "../tags/noncopyable.h"
00010 #include <windows.h>
00011 
00012 namespace lean
00013 {
00014 namespace concurrent
00015 {
00016 
00018 class semaphore : public noncopyable
00019 {
00020 private:
00021     HANDLE m_semaphore;
00022 
00023 public:
00025     explicit semaphore(long initialCount = 1)
00026         : m_semaphore( ::CreateSemaphoreW(NULL, initialCount, LONG_MAX, NULL) )
00027     {
00028         LEAN_ASSERT(m_semaphore != NULL);
00029     }
00031     ~semaphore()
00032     {
00033         ::CloseHandle(m_semaphore);
00034     }
00035 
00037     LEAN_INLINE bool try_lock()
00038     {
00039         return (::WaitForSingleObject(m_semaphore, 0) == WAIT_OBJECT_0);
00040     }
00041 
00043     LEAN_INLINE void lock()
00044     {
00045         DWORD result = ::WaitForSingleObject(m_semaphore, INFINITE);
00046         LEAN_ASSERT(result == WAIT_OBJECT_0);
00047     }
00048 
00050     LEAN_INLINE void unlock()
00051     {
00052         BOOL result = ::ReleaseSemaphore(m_semaphore, 1, NULL);
00053         LEAN_ASSERT(result != FALSE);
00054     }
00055 
00057     LEAN_INLINE HANDLE native_handle() const
00058     {
00059         return m_semaphore;
00060     }
00061 };
00062 
00063 } // namespace
00064 
00065 using concurrent::semaphore;
00066 
00067 } // namespace
00068 
00069 #endif