簡體   English   中英

C ++-Boost Thread / Bind / Shared_ptr:斷言錯誤

[英]C++ - Boost Thread/Bind/Shared_ptr : Assert fault

我有一個小問題無法解決。 我正在做一個小型服務器,將我的系統日志消息重定向到該服務器。 這是非常基本的,但是我想知道我做錯了什么,因為當我調用join ()時,出現以下錯誤:

/boost/path/shared_ptr.hpp:418: T* boost::shared_ptr< <template-parameter-1-1> >::operator->() const [with T = boost::thread]: Assertion `px != 0' failed.

該代碼將解釋更多:

class SysLogServer
{
public:

  typedef boost::shared_ptr<boost::thread>  Ptr_thread;

  bool Start ()
  {
    ...
    _thrd = Ptr_thread(new boost::thread (boost::bind(&SysLogServer::run, this)));
    if (!_thrd.get ())
      return ERROR ("Thread couldn't be instanciated.");
    ...
  }

  bool Stop ()
  {
    ...
    _thrd->join ();
    ...
  }

private:

  void run()
  {
    ...
  }

  Ptr_thread _thrd;

};

非常感謝您的幫助。

PS:如果有任何改進可以提高“線程安全性”,請告訴我,因為它確實使我很感興趣:)

編輯:

謝謝您的評論,我認為shared_ptr在那里確實沒有用,但是從boost::enable_shared_from_this繼承該類以確保在線程結束之前不釋放該類(這不應該發生)可能對我有用。

Start()當然是之前調用的Stop()我執行與一個簡單的檢查state屬性。 run()方法只是接受連接。

class SysLogServer
{
public:

  bool Start ()
  {
    ...
    _thrd = boost::thread(boost::bind(&SysLogServer::run, this)));
    ...
  }

  bool Stop ()
  {
    ...
    _thrd.join();
    ...
  }

  void run ()
  {
    std::cout << "Start running..." << std::endl; // never printed
    // Create a socket
    // Create a sockaddr_in
    // Bind them together
    while (!_serverStopped && !listen(sockfd, 5)) // on Stop(): _severStopped = true
     {
       // Get socket from accept
       // Print the received data
       // Close the socket given by accept
     }
    // close the first socket
  }

  boost::thread _thrd;
};

現在可以使用了。 我以前使用幾乎與指針相同的解決方案,但沒有成功,我的朋友SIGSEGV :)

編輯2:

它不適用於指針,因為我忘記了在Stop()中檢查服務器已啟動。 Start()方法由於另一個原因而失敗。

感謝您的有用建議

斷言的原因不能從您在此處提供的代碼中立即看出來,但是盡管如此,仍可以對代碼進行重大改進。

您似乎正在使用shared_ptr ,但似乎沒有任何需要。 可以將Ptr_thread更改為boost::thread 這將導致更簡單,更有效的代碼,並更易於理解對象的生命周期。

然后可以將代碼更改為:

class SysLogServer
{
public:

  bool Start ()
  {
      ...
      _thrd = boost::thread(boost::bind(&SysLogServer::run, this)));
      ...
  }

  bool Stop ()
  {
      ...
      _thrd.join();
      ...
  }

private:

    void run()
    {
        ...
    }

    boost::thread _thrd;

};

如果在調用Start()之前調用Stop()則此代碼仍然不正確,這是原始代碼失敗的唯一明顯說明。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM