在Java中,我们可以创建一个类
class Test {
public synchronized void fn1() {
}
public synchronized void fn2() {
}
public synchronized void fn3() {
fn1(); // Calling another method
}
}
在C ++中,如果我想模仿功能,一种方法是
class Test {
private:
mutex obj;
public:
void fn1(bool calledFromWithinClass = false) {
if(calledFromWithinClass)
fn1Helper();
else
unique_lock<mutex> lock(obj);
fn1Helper();
}
void fn2(bool calledFromWithinClass = false) {
if(calledFromWithinClass)
fn2Helper();
else
unique_lock<mutex> lock(obj);
fn2Helper();
}
void fn3(bool calledFromWithinClass = false) {
if(calledFromWithinClass)
fn3Helper();
else {
unique_lock<mutex> lock(obj);
fn3Helper();
}
}
private:
void fn1Helper() {
}
void fn2Helper() {
}
void fn3Helper() {
fn1(true);
}
}
int main() {
Test obj;
obj.fn1();
obj.fn2();
// i.e from outside the class the methods are called with calledFromWithinClass as false.
}
简而言之,我要做的就是使用RAII进行锁定以及允许函数相互调用。在C ++中,如果没有外部函数已获取锁,则内部函数无法获取该锁,并且代码被卡住。
如您所见,代码很复杂,在C ++中还有其他方法可以做到这一点。
我只能使用C ++ 98,并且可以假定该类中的所有方法都是同步的(即需要锁)
我可以提出两种选择:
只需使用boost::recursive_mutex
代替(或std::recursive_mutex
在C ++ 11中)。
(更好)始终从您的同步代码中调用非同步的私有实现:
class Test {
private:
mutex obj;
public:
void fn1() {
unique_lock<mutex> lock(obj);
fn1Helper();
}
void fn2(bool calledFromWithinClass = false) {
unique_lock<mutex> lock(obj);
fn2Helper();
}
private:
void fn1Helper() {
}
void fn2Helper() {
fn1Helper();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句