0

我有一个我无法解决的小问题。我正在制作一个小型服务器来将我的系统日志消息重定向到它。这是非常基本的,但我想知道我做错了什么,因为当我打电话时我一直有以下错误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()进行了简单的检查。staterun()方法只是接受连接。

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()方法因另一个原因而失败。

感谢您提供有用的建议

4

1 回答 1

1

从您在此处提供的代码中无法立即清楚地看到断言的原因,但尽管如此,该代码仍可以显着改进。

您似乎正在使用 a shared_ptr,但似乎没有任何需要。Ptr_thread可以改为 just 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;

};

Stop()如果在调用之前调用过此代码仍然不正确Start(),这是原始代码失败的唯一明显解释。

于 2011-10-07T10:18:27.040 回答