我正在基于boost网站上的示例构建应用程序 . 以下是相关的定义:
typedef boost::shared_ptr< connection > connection_ptr;
std::set< connection_ptr> connections_;
std::vector< boost::shared_ptr< boost::thread> > threads;
其中连接是一个类 .
在其中一个文件connection_manager.cpp中,它们的行为如下:
void connection_manager::start(connection_ptr c)
{
connections_.insert(c);
c->start();
}
现在,由于我的程序结构,我想在一个单独的线程中启动每个新连接 . 所以我根据以下修改了上述内容:
void connection_manager::start(connection_ptr c)
{
boost::shared_ptr< boost::thread > thread(new boost::thread(
boost::bind(&connection::start, c)));
// push the newely created thread into the vector
threads.push_back(thread);
// save the connection in our set
connections_.insert(c);
}
我的问题,也就是这个问题,就是当我只想要其中一个connection_对象时 . 在前面提供的链接中,他们喜欢这样:
void connection_manager::stop(connection_ptr c)
{
connections_.erase(c);
c->stop();
// find the connection in among the threads and join that thread
}
但正如上面的评论所暗示的,我如何在所有线程中找到c并仅停止该线程 . 我想为该线程调用join()函数 .
更新:
我认为这实际上是我真正想拥有的!所以我将我的变量声明为
std::map < connection_ptr, boost::shared_ptr < boost::thread > > threads;
但是,我如何以与以前相同的方式创建新的胎面?喜欢:
boost::shared_ptr < boost::thread > thread(new boost::thread(
boost::bind(&connection::start, c)));
但接下来又是什么呢?抱歉感到困惑...... :-)
2 回答
如果使用映射(或其他关联容器)而不是向量,则可以维护连接和线程之间的关联:
允许你写:
创建线程后,而不是push_back调用,然后:
稍后你想要查找它 .
注意:作为一般性评论,在线程和网络连接之间保持1:1映射的应用程序非常容易受到拒绝服务(DoS)攻击 .
如果您的连接始终绑定到一个线程,那么简单地让连接对象指向它正在运行的线程并将线程中的启动逻辑移动到连接类本身是有意义的 .