gpt4 book ai didi

c++ - C++ 中发送者-接收者模型中的多线程

转载 作者:行者123 更新时间:2023-11-28 01:43:02 25 4
gpt4 key购买 nike

我正在尝试用 C++ 构建一个发送者-接收者模型。我想以前馈方式将数据从发送方发送到接收方。简而言之,所需的架构可以这样表示(基本单元称为节点):

Each node can receive (send) data from (to) another node. Each node has as many as desired senders (receivers). Each node has a number called impulse which is data supposed to be sent. Let's call one data propagation through a whole network a cycle. Then in one cycle each node that belongs to the network must send impulse once and only once to all its receivers.

下面是上述想法的初步实现。

class Node
{
private :
double in_signal;//received data
double out_signal;//data to send
bool is_opened;//status of channel

void update_in( double package );//receive new package

protected :
std::vector<Node*> receivers;

public :
Node( double out_signal )
: in_signal(0.),
out_signal(out_signal),
is_opened(false)
{}
~Node() {}

void add_receiver( Node* receiver );
void emit();//send out_signal or impulse
};

void Node::update_in( double package )
{
//the problem is how to control the status of the channel:
//it must be closed after getting all data
if ( not is_opened )
{
in_signal = 0.;//reset
is_opened = true;
}
in_signal += package;
}

void Node::add_receiver( Node* receiver )
{
receivers.push_back( receiver );
}

void Node::emit()
{
for ( auto& receiver : receivers )
{
receiver->update_in( out_signal );
}
}

我无法解决的问题是这个架构背后的多线程:

The node's in_signal can be updated by several senders, but senders work independently (required) therefore I am afraid of arising concurrency.


所以我想问一下

  1. 如何解决这个多读问题?
  2. 如何确定是否已收到所有数据?

我会感谢一些想法、模式、概念等。

最佳答案

首先,恕我直言,这是对您的问题的过度简化。我认为,例如,您的数据不能简单地是 double

无论如何:

  1. 如果在您的架构中存在竞争条件(如果每个节点都有自己的线程,那么您显然存在竞争条件),除了mutex,我看不到任何解决方案。
  2. 这取决于实际任务的庞大性和复杂性,但您可以应用一些规则让节点能够理解数据包的生命周期(一些想法:数据包的序列号、近节点列表等)。

关于c++ - C++ 中发送者-接收者模型中的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46403264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com