From c8e719101e86b656b2b5fc80e87703ea2956bf2f Mon Sep 17 00:00:00 2001 From: Matthieu Gautier Date: Thu, 8 Aug 2019 15:13:14 +0200 Subject: [PATCH] Add a new tool `Lock` to lock a mutex. And automaticlly unlock it when the `Lock` got out of scope. --- include/meson.build | 1 + include/tools/lock.h | 46 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 include/tools/lock.h diff --git a/include/meson.build b/include/meson.build index 045b7387d..b6e95a886 100644 --- a/include/meson.build +++ b/include/meson.build @@ -22,6 +22,7 @@ install_headers( 'tools/pathTools.h', 'tools/regexTools.h', 'tools/stringTools.h', + 'tools/lock.h', subdir:'kiwix/tools' ) diff --git a/include/tools/lock.h b/include/tools/lock.h new file mode 100644 index 000000000..98c64937a --- /dev/null +++ b/include/tools/lock.h @@ -0,0 +1,46 @@ + + +#ifndef KIWIXLIB_TOOL_LOCK_H +#define KIWIXLIB_TOOL_LOCK_H + +#include + +namespace kiwix { + +class Lock +{ + public: + explicit Lock(pthread_mutex_t* mutex) : + mp_mutex(mutex) + { + pthread_mutex_lock(mp_mutex); + } + ~Lock() { + if (mp_mutex != nullptr) { + pthread_mutex_unlock(mp_mutex); + } + } + Lock(Lock && other) : + mp_mutex(other.mp_mutex) + { + other.mp_mutex = nullptr; + } + Lock & operator=(Lock && other) + { + mp_mutex = other.mp_mutex; + other.mp_mutex = nullptr; + return *this; + } + + + private: + pthread_mutex_t* mp_mutex; + + Lock(Lock const &) = delete; + Lock & operator=(Lock const &) = delete; +}; + + +} + +#endif //KIWIXLIB_TOOL_LOCK_H