2016-03-02 166 views
3

在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,你可以假設類中的所有方法都是同步的(即需要輸入鎖)

+0

可能的複製(HTTP://計算器。 com/questions/5429653/what-is-correspoding-feature-for-synchronized-in-java) –

+0

我不記得'std :: recursive_mutex'是否在C++ 98中。如果是這樣,互斥量可以簡單地換出遞歸互斥量,讓您在每種方法中無條件地獲取互斥量。故事結局。 –

+1

你需要在這些'else'塊上加一些大括號。 – aschepler

回答

3

我可以建議兩個選項:

  1. 剛改爲使用boost::recursive_mutex(或在C++ 11中使用std::recursive_mutex)。

  2. (更好)始終呼叫非同步私有實現從同步代碼:?什麼是correspoding功能在Java同步]的

    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(); 
        } 
    } 
    
+0

我喜歡選項號碼1,我將使用遞歸鎖....感謝 – user1918858

相關問題