2013-08-21 104 views
3

我試圖訪問一個共享的std ::隊列使用std :: mutex和std :: lock_guard。互斥體(pending_md_mtx_)是另一個對象(其地址有效)的成員變量。我的代碼似乎是在構建lock_guard時發生的故障。std :: lock_guard <std::mutex>段建設?

任何想法?我應該使用std :: unique_lock(或其他對象)嗎?在Ubuntu Linux下運行GCC 4.6(--std = C++ 0x)。我無法發佈整個班級,但只能訪問下面列出的互斥和隊列。

template <typename ListenerT> 
class Driver 
{ 
public: 
    template <typename... Args> 
    Driver(Args&&... args) : 
     listener_(std::forward<Args>(args)...) {} 

    void enqueue_md(netw::Packet* packet) 
    { 
     std::lock_guard<std::mutex> lock(pending_md_mtx_); 
     pending_md_.push(packet); 
    } 

    void process_md() 
    { 
     std::lock_guard<std::mutex> lock(pending_md_mtx_); 
     while (pending_md_.size()) 
     { 
      netw::Packet* pkt=pending_md_.front(); 
      pending_md_.pop(); 
      process_md(*pkt); 
     } 
    } 
    //... Other code which I can't post... 

private: 
    ListenerT listener_; 
    std::mutex pending_md_mtx_; 
    std::queue<netw::Packet*> pending_md_; 
}; 

GDB堆棧跟蹤:

(gdb) bt 
#0 __pthread_mutex_lock (mutex=0x2f20aa75e6f4000) at pthread_mutex_lock.c:50 
#1 0x000000000041a2dc in __gthread_mutex_lock (__mutex=0xff282ceacb40) at /usr/include/c++/4.6/x86_64-linux-gnu/./bits/gthr-default.h:742 
#2 lock (this=0xff282ceacb40) at /usr/include/c++/4.6/mutex:90 
#3 lock_guard (__m=..., this=0x7f2874fc4db0) at /usr/include/c++/4.6/mutex:445 
#4 driver::Driver<Listener, false>::enqueue_md (this=0xff282ceac8a0, packet=...) at exec/../../driver/Driver.hpp:95 
+2

您需要更多地瞭解'pending_md_mtx_'是如何聲明和訪問的。 –

+1

錯誤不在顯示的代碼中:http://coliru.stacked-crooked.com/view?id=c2f3e1d151aa3606419ef41ac77-f0f4984a193759175f04eadfe43758cb – sehe

+1

您使用的驅動程序「」的*實例*的遠程可能不是有效?例如'Driver * p; p-> enqueue_md(param);''一定會*編譯*,但同樣肯定會調用未定義的行爲,因爲這個實例是完全無效的。 – WhozCraig

回答

0

最近我遇到了這個問題。這是由一行代碼在獲得鎖後導致緩衝區溢出引起的。看起來很奇怪的是,鎖之下的一行代碼會導致問題提前幾行,但我認爲緩衝區溢出會導致一些損壞,從而導致第二次調用該函數時出現問題。

0

我在構建std::lock_guard時遇到了段錯誤,結果我的代碼使用了未初始化的std::shared_ptr<my_object_with_mutex>。使用正確構造的my_object_with_mutex可以解決問題。

相關問題