![]() |
libfilezilla
|
00001 #ifndef LIBFILEZILLA_MUTEX_HEADER 00002 #define LIBFILEZILLA_MUTEX_HEADER 00003 00007 #include "libfilezilla.hpp" 00008 #include "time.hpp" 00009 00010 #ifdef FZ_WINDOWS 00011 #include "private/windows.hpp" 00012 #else 00013 #include <pthread.h> 00014 #endif 00015 00016 namespace fz { 00017 00027 class FZ_PUBLIC_SYMBOL mutex final 00028 { 00029 public: 00030 explicit mutex(bool recursive = true); 00031 ~mutex(); 00032 00033 mutex(mutex const&) = delete; 00034 mutex& operator=(mutex const&) = delete; 00035 00037 void lock(); 00038 00040 void unlock(); 00041 00042 private: 00043 friend class condition; 00044 friend class scoped_lock; 00045 00046 #ifdef FZ_WINDOWS 00047 CRITICAL_SECTION m_; 00048 #else 00049 pthread_mutex_t m_; 00050 #endif 00051 }; 00052 00061 class FZ_PUBLIC_SYMBOL scoped_lock final 00062 { 00063 public: 00064 explicit scoped_lock(mutex& m) 00065 : m_(&m.m_) 00066 { 00067 #ifdef FZ_WINDOWS 00068 EnterCriticalSection(m_); 00069 #else 00070 pthread_mutex_lock(m_); 00071 #endif 00072 } 00073 00074 ~scoped_lock() 00075 { 00076 if (locked_) { 00077 #ifdef FZ_WINDOWS 00078 LeaveCriticalSection(m_); 00079 #else 00080 pthread_mutex_unlock(m_); 00081 #endif 00082 } 00083 00084 } 00085 00086 scoped_lock(scoped_lock const&) = delete; 00087 scoped_lock& operator=(scoped_lock const&) = delete; 00088 00093 void lock() 00094 { 00095 locked_ = true; 00096 #ifdef FZ_WINDOWS 00097 EnterCriticalSection(m_); 00098 #else 00099 pthread_mutex_lock(m_); 00100 #endif 00101 } 00102 00107 void unlock() 00108 { 00109 locked_ = false; 00110 #ifdef FZ_WINDOWS 00111 LeaveCriticalSection(m_); 00112 #else 00113 pthread_mutex_unlock(m_); 00114 #endif 00115 } 00116 00117 private: 00118 friend class condition; 00119 00120 #ifdef FZ_WINDOWS 00121 CRITICAL_SECTION * const m_; 00122 #else 00123 pthread_mutex_t * const m_; 00124 #endif 00125 bool locked_{true}; 00126 }; 00127 00132 class FZ_PUBLIC_SYMBOL condition final 00133 { 00134 public: 00135 condition(); 00136 ~condition(); 00137 00138 condition(condition const&) = delete; 00139 condition& operator=(condition const&) = delete; 00140 00147 void wait(scoped_lock& l); 00148 00160 bool wait(scoped_lock& l, duration const& timeout); 00161 00171 void signal(scoped_lock& l); 00172 00180 bool signalled(scoped_lock const&) const { return signalled_; } 00181 private: 00182 #ifdef FZ_WINDOWS 00183 CONDITION_VARIABLE cond_; 00184 #else 00185 pthread_cond_t cond_; 00186 #endif 00187 bool signalled_{}; 00188 }; 00189 00190 } 00191 #endif