在Java中,我們可以創建一個類類與C++的所有synchronized方法
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++中沒有calledFromWithinClass標誌的情況下,內部函數不能獲取該鎖並且代碼被卡住。
正如你所看到的代碼是複雜的,是否有任何其他方式在C++中做到這一點。
我只能用C++ 98,你可以假設類中的所有方法都是同步的(即需要輸入鎖)
可能的複製(HTTP://計算器。 com/questions/5429653/what-is-correspoding-feature-for-synchronized-in-java) –
我不記得'std :: recursive_mutex'是否在C++ 98中。如果是這樣,互斥量可以簡單地換出遞歸互斥量,讓您在每種方法中無條件地獲取互斥量。故事結局。 –
你需要在這些'else'塊上加一些大括號。 – aschepler