为自定义库实现lock_guard的正确C ++方法 [英] Proper C++ way of implementing a lock_guard for custom library
问题描述
O明智的互连网
我们两个同事之间陷入僵局,我们可以利用您的帮助以正确的C ++方式解决问题.基本上,我们有一组实用程序类,其中两个是Mutex和SpinLock类,它们都具有以下简化接口:
We have an impasse between two colleagues that we could use your help resolving in the proper C++ way. Basically we have a set of utility classes, two of which are a Mutex and SpinLock class which both have the following abridged interface:
class Mutex {
public:
Mutex();
~Mutex();
void Lock();
void Unlock();
// ...
};
显然,这与std :: lock_guard所使用的BasicLockable概念相似,但用不同的大小写,因此我们需要类似的东西(假设Mutex类在此示例中是不可变的;我们无法向其添加BasicLockable概念).同样,并非我们所有支持平台的编译器都具有c ++ 11的全部功能,因此我们不能仅使用香草c ++ 11的支持.
Obviously this is similar to, but differently-cased than the BasicLockable concept used by std::lock_guard, so we want something similar (assume that the Mutex class is immutable in this example; we cannot add the BasicLockable concept to it). Also not all of our compilers for supported platforms are fully c++11 featured, so we cannot just use vanilla c++11 support.
一个思路是通用保护类的以下实现,可以将其继承以提供通用保护类,并从其继承以创建锁保护类:
One school of thought is the following implementation of a generic guard class which can be inherited to provide a generic guard class and inherit from it to create a lock-guard class:
template<class T, void (T::*EnterFn)(), void (T::*ExitFn)()>
class Guard
{
public: // copy constructor deleting omitted for brevity
Guard( T *lock ) : m_lock(lock) { (m_lock->*EnterFn)(); }
~Guard(); { (m_lock->*ExitFn)(); }
private:
T *m_lock;
};
template<class T>
class LockGuard : public Guard<T, &T::Lock, &T::Unlock>
{
public:
LockGuard(const T* lock) : Guard<T, &T::Lock, &T::Unlock>(lock) {}
};
另一种思路是仅仅实现一个简单的锁卫:
The other school of thought is to just implement a simple lockguard:
template<class T>
class LockGuard {
T* m_lockable;
public:
LockGuard(const T* lockable) : m_lockable(lockable) { lockable->Lock(); }
~LockGuard() { m_lockable->Unlock(); }
};
您会选择哪种实施方式,为什么?什么是最合适的 C++(03, 11, 14, 17) 实现方式?如上所述,拥有通用的Guard类是否有任何内在的价值?
Which implementation would you choose and why? What is the most proper C++(03, 11, 14, 17) way of implementing it? Is there any inherent value to having a generic Guard class as described above?
推荐答案
我将在您的标题中回答该问题,因为没有其他人回答.
I'll answer the question in your title since nobody else answered it.
根据文档, lock_guard
适用于满足 BasicLockable
要求"的任何类型. BasicLockable 仅需要两种方法, lock()
和 unlock()
.
According to the docs, lock_guard
works on any type that "meets the BasicLockable
requirements". BasicLockable only requires two methods, lock()
and unlock()
.
为了使 lock_guard
与自定义库一起使用,您需要向 lock()
和 unlock()
方法中添加库的互斥锁类,或将其包装在另一个具有 lock()
和 unlock()
方法的类中.
In order to make lock_guard
work with a custom library, you need to either add lock()
and unlock()
methods to the library's mutex class, or wrap it in another class that has lock()
and unlock()
methods.
这篇关于为自定义库实现lock_guard的正确C ++方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!