From 9a0cff2a002e7dbf33172c56a7e72d884207daf9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beat=20K=C3=BCng?= Date: Fri, 22 Apr 2016 18:37:39 +0200 Subject: [PATCH] vdev: add a SmartLock class that automatically unlocks when going out of scope --- src/drivers/device/vdev.h | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/drivers/device/vdev.h b/src/drivers/device/vdev.h index 593dea6143..3875ea7706 100644 --- a/src/drivers/device/vdev.h +++ b/src/drivers/device/vdev.h @@ -196,6 +196,26 @@ protected: px4_sem_post(&_lock); } + /** + * @class Smart locking object that uses the same lock as lock(), but automatically + * takes the lock when created and releases the lock when the object goes out of + * scope. Use like this: + * { + * SmartLock smart_lock(*this); + * //critical section start + * ... + * //critical section end + * } + */ + class SmartLock + { + public: + SmartLock(Device &device) : _device(device) { _device.lock(); } + ~SmartLock() { _device.unlock(); } + private: + Device &_device; + }; + private: px4_sem_t _lock; /**< lock to protect access to all class members (also for derived classes) */