]> git.tdb.fi Git - libs/core.git/blobdiff - source/core/mutex.cpp
Refactor Mutex with pimpl
[libs/core.git] / source / core / mutex.cpp
diff --git a/source/core/mutex.cpp b/source/core/mutex.cpp
new file mode 100644 (file)
index 0000000..e1657c9
--- /dev/null
@@ -0,0 +1,62 @@
+#ifndef WIN32
+#include <cerrno>
+#endif
+#include "mutex.h"
+#include "mutex_private.h"
+#include "systemerror.h"
+
+namespace Msp {
+
+Mutex::Mutex():
+       priv(new Private)
+{
+#ifdef WIN32
+       InitializeCriticalSection(&priv->crit);
+#else
+       pthread_mutex_init(&priv->mutex, 0);
+#endif
+}
+
+Mutex::~Mutex()
+{
+#ifdef WIN32
+       DeleteCriticalSection(&priv->crit);
+#else
+       pthread_mutex_destroy(&priv->mutex);
+#endif
+       delete priv;
+}
+
+void Mutex::lock()
+{
+#ifdef WIN32
+       EnterCriticalSection(&priv->crit);
+#else
+       if(int err = pthread_mutex_lock(&priv->mutex))
+               throw system_error("Mutex::lock", err);
+#endif
+}
+
+bool Mutex::trylock()
+{
+#ifdef WIN32
+       return TryEnterCriticalSection(&priv->crit);
+#else
+       int err = pthread_mutex_trylock(&priv->mutex);
+       if(err && err!=EBUSY)
+               throw system_error("Mutex::trylock", err);
+       return !err;
+#endif
+}
+
+void Mutex::unlock()
+{
+#ifdef WIN32
+       LeaveCriticalSection(&priv->crit);
+#else
+       if(int err = pthread_mutex_unlock(&priv->mutex))
+               throw system_error("Mutex::unlock", err);
+#endif
+}
+
+} // namespace Msp