我有一个我无法解决的小问题。我正在制作一个小型服务器来将我的系统日志消息重定向到它。这是非常基本的,但我想知道我做错了什么,因为当我打电话时我一直有以下错误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()
方法因另一个原因而失败。
感谢您提供有用的建议