Add a new tool `Lock` to lock a mutex.

And automaticlly unlock it when the `Lock` got out of scope.
This commit is contained in:
Matthieu Gautier 2019-08-08 15:13:14 +02:00
parent 1b8e7849bd
commit c8e719101e
2 changed files with 47 additions and 0 deletions

View File

@ -22,6 +22,7 @@ install_headers(
'tools/pathTools.h', 'tools/pathTools.h',
'tools/regexTools.h', 'tools/regexTools.h',
'tools/stringTools.h', 'tools/stringTools.h',
'tools/lock.h',
subdir:'kiwix/tools' subdir:'kiwix/tools'
) )

46
include/tools/lock.h Normal file
View File

@ -0,0 +1,46 @@
#ifndef KIWIXLIB_TOOL_LOCK_H
#define KIWIXLIB_TOOL_LOCK_H
#include <pthread.h>
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