2016-01-04 188 views
1

我不能從這個死鎖出不來。首先,讓我想要實現我的話解釋:C++線程死鎖

  1. 主要創建一個線程並等待線程完成首次
  2. 線程獲取鎖從源讀取和他一樣多能,(填充緩衝器和其標記爲滿),釋放鎖,只有當所有緩衝區已滿,並在結束時,他通知給主要的緩衝區都是滿
  3. 主要獲取鎖,消耗2個緩衝區,在最後將它們標記作爲自由填寫,並喚醒該線程再次釋放鎖 等。 (有物體(數組+布爾),與所述陣列I表示緩衝器和與所述布爾變量主/螺紋標記緩衝液作爲空/滿)。 我所做的是這個(在c++實現):

    mutex m; //mutex and condition variable are global variables 
    condition_variable cv; 
    
    void func_executed_by_thread(params){ 
        std::unique_lock<std::mutex> lk(m); 
        cv.wait(lk); 
        //put stuff inside buffers 
        //mark buffer as full 
        lk.unlock(); 
        cv.notify_one(); 
    } 
    
    int main(int argc, char**argv){ 
        //allocating space for buffer 
        std::thread worker(func_executed_by_thread,params); 
        while(true){ 
         std::unique_lock<std::mutex> lk(m); 
         cv.wait(lk); 
         //get two buffer to consume 
         //consume two buffer 
         //mark these two buffer as empty 
         lk.unlock(); 
         cv.notify_one(); 
         //do some other stuff that takes long time (but in the meanwhile the other thread should empty the other buffer) 
    
        } 
    

    }

的問題是,線程僅適用於第一次,則主要消耗2個緩衝區,線程永遠不會獲得鎖再次鎖定並且無限循環while(true)被鎖定。

+0

不要先檢查你正在等待的東西是否已經發生,否則不要在條件變量上調用'wait'。 (這是你在調用'wait'之前獲得鎖的原因。) –

回答

1

從看你的代碼,該功能只func_executed_by_thread()被調用一次。要麼你就必須創建多個線程的while(true)內或有func_executed_by_thread()包含一個循環爲好。