等待条件的非线程替代方案.(编辑:Proactor模式与boost.asio?)

Non-threaded alternative to waiting on a condition. (Edit: Proactor pattern with boost.asio?)

本文关键字:模式 Proactor boost asio 编辑 条件 线程 方案 等待      更新时间:2023-10-16

我正在实现一个消息传递算法。当相邻节点上有足够的信息来组成消息时,消息就会在相邻节点之间传递——这些信息是从相邻节点传递到该节点的。如果我将每个消息都设置为一个线程,并使用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。当你不是在等待操作系统,而是在等待应用程序中的另一个消息源时,他们会为你提供相应的工具。