等待条件的非线程替代方案.(编辑:Proactor模式与boost.asio?)
Non-threaded alternative to waiting on a condition. (Edit: Proactor pattern with boost.asio?)
我正在实现一个消息传递算法。当相邻节点上有足够的信息来组成消息时,消息就会在相邻节点之间传递——这些信息是从相邻节点传递到该节点的。如果我将每个消息都设置为一个线程,并使用boost::condition将线程置于睡眠状态,直到所需的信息可用,那么实现就很简单了。
不幸的是,我在图中有100k个节点,这意味着300k个线程。当我问如何制作这么多线程时,答案是我不应该——而是重新设计。
我的问题是:是否存在等待条件的标准设计模式?也许是一些异步控制模式?
EDIT:我想我可以用因子模式做到这一点。我已经编辑了一些标签,包括boost::asio -看看是否有人对此有建议。
所以讨论可以是具体的,下面是目前为止如何定义消息的:
class
Message
{
public:
Message(const Node* from, Node* to)
: m_from(from), m_to(to)
{}
void
operator()()
{
m_to->ReceiveMessage( m_from->ComposeMessage() );
}
private:
Node *m_from, *m_to;
};
这些消息函子目前由boost::thread启动。然后是
class Node
{
Node(Node* Neighbour1, Node* Neighbour2, Node* Neighbour3);
// The messages (currently threads) are created on construction,
// The condition locks then sort out when they actually get passed
// without me having to think too hard.
void ReceiveMessage(const Message&);
//set m_message from received messages;
//EDIT This looks like an async write - use boost asio here?
Message
ComposeMessage()
{
// If possible I want to implement this function without threads
// It works great but it if every message is a thread
// then I have 300k threads.
// EDIT: this looks like an async read (use boost asio here?)
boost::mutex::scoped_lock lock(m_mutex);
while (!m_message) //lock the thread until parameter is set.
m_cond.wait(lock);
return *m_message;
}
private:
boost::optional<Message> m_message;
boost::mutex m_mutex;
boost::condition m_cond;
}
我喜欢代码的透明度,如果可能的话,我想通过一些替代条件锁的方法来保持相同的接口。
我猜你正在寻找的是反应堆模式。在这种情况下,大多数活动不会花费太多时间,他们正在进行合作多任务处理。关于这个想法的JavaScript实现,请参阅node.js,但在c++中,ACE库提供了这个概念,允许基于系统中内核数量的多个线程。
这些库都依赖于一些支持磁盘、网络等非阻塞IO的操作系统api。当你不是在等待操作系统,而是在等待应用程序中的另一个消息源时,他们会为你提供相应的工具。
相关文章:
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 为什么在保护模式下继承升级不起作用
- 如何在全屏模式下(在OpenGL中)使背景透明
- 为什么使用__LINE_的代码在发布模式下在MSVC下编译,而不是在调试模式下
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 此模式的C++RegEx
- avrogencpp能为模式中的每种类型生成单独的头文件吗
- 使用可变模板的Broadcaster/Listener模式
- c++方法参数只能在linux的发布模式下自行更改
- 资源管理设计模式
- 使用 mod_gsoap 部署服务时,如何在 Gsoap 中更改 soap 上下文的模式?
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 小字符串优化(调试与发布模式)
- 可视化C++:发布模式的运行时库作为'Multi-threaded Debug DLL'
- 如何设计具有不同类型的通知和观察器的观察者模式?
- 在C++的一系列数字中查找重复模式
- 是否允许使用带有"w+"模式的 freopen 进行标准设置?
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 如果 Proactor 设计模式优于异步 I/O,为什么它在 ASIO 中不是默认值?
- 等待条件的非线程替代方案.(编辑:Proactor模式与boost.asio?)