Herb Sutter 在关于 C++11 和并发的演讲中提出了这个问题(请参阅此视频)
这里的关键思想是有一个非锁定类X
,其中每个函数调用都应该用一个在函数之后解锁的锁来装饰。
然而,Herb Sutter 又偏离了方向,提出了一种基于函子的方法。我想知道是否甚至可以使用 C++11 以通用方式使用类的锁定和解锁来包装每个函数调用(而不是手动包装每个函数调用)。
class X {
public:
X() = default;
void somefunc(arg1 x1, arg2 x2, ...);
void somefunc2(arg1 x1, arg2 x2, ...);
/* and more */
};
// herb admits one way to make all functions *available*
// in another class is by derivation
class XX : public X {
public:
XX() = default;
// all functions available in NON overloaded form...
};
还有装饰器模式
class XXX {
public:
XXX(X &x) : m_x(x) {}
// explicitly call each wrapped function ... done for each class separately.
void somefunc(arg1 x1, arg2 x2, ...);
void somefunc2(arg1 x1, arg2 x2, ...);
private:
class X& m_x;
};
但是有没有这样的可能:
template<>
class wrap_everything;
wrap_everything<X> x;
x.somefunc(x1,x2,...); // this is then locked.
为了完整起见,这是草本萨特基于函子的方法:
template <class T> class locker {
private:
mutable T m_t;
mutable std::mutex m_m;
public:
locker( T t = T{} ) : m_t(t) {}
template <typename F>
auto operator()(F f) const -> decltype(f(m_t)) {
std::lock_guard<mutex> _{m_m};
return f(t);
}
};
// usage
locker<std::string> s;
s([](string &s) {
s += "foobar";
s += "barfoo";
});