繁体   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