C ++异步代理奇怪的行为

时间:2016-12-29 10:51:24

标签: c++ asynchronous

我从这里开始使用basic-agents.cpp Asynchronous Agents但我想测试一个循环,所以我做了

class agent1 : public agent
{
public:
    explicit agent1(ISource<int>& source, ITarget<string>& target)
        : _source(source)
        , _target(target)
    {
    }

protected:
void run()
{
    std::cout << "type: ";
    std::string a;
    std::getline(std::cin, a);

    // send the request
    std::cout << "agent1: sending request... " << endl;

    send(_target, a);

    // Read the response
    int response = receive(_source);

    std::cout << "agent1: received '" << response << "'." << endl;

    // move the agent to the finished state.
    done();
    }

private:
    ISource<int>& _source;
    ITarget<string >& _target;
};

和agent2

class agent2 : public agent
{
public:
    explicit agent2(ISource<string>& source, ITarget<int>& target)
        : _source(source)
        , _target(target)
    {
    }

protected:
void run()
{
    // read the request
    string request = receive(_source);

    std::cout << "agent2: received '" << request << "'." << std::endl;

    // send the response
    std::cout << "agent2: sending response..." << std::endl;

    code += 1;
    send(_target, code);

    // move the agent to the finished state
    done();

public:
    int code;
private:
    ISource<string>& _source;
    ITarget<int>& _target;
};

和主要运行代理

    int oldcode = 0;
    while (oldcode < 10)
    {
        agent1 first_agent(buffer2, buffer1);
        agent2 second_agent(buffer1, buffer2);
        second_agent.code = oldcode;

        // Step 3: start the agents.  The runtime calls the run method on each agent.
        first_agent.start();
        second_agent.start();

        // Step 4: wait for both agents to finish
        agent::wait(&first_agent);
        agent::wait(&second_agent);
        oldcode = second_agent.code;
        std::cout << "In Step 2 loop, oldcode: " << oldcode << std::endl;
    }

我得到的有趣的是这个输出

type: a
agent1: sending request...
agent2: received 'a'.
agent2: sending response...
agent1: received '1'.
In Step 2 loop, oldcode: 1
type: b
agent1: sending request...
agent1: received '1'.
agent2: received 'b'.
agent2: sending response...
In Step 2 loop, oldcode: 2
type: c
agent1: sending request...
agent1: received '2'.
agent2: receivede 'c'.
agent2: sending response...
In Step 2 loop, oldcode: 3

请注意,代理1报告在开始时两次接收'1',并且在响应'b'时接收到无序接收。这不会发生在任何其他地方并且是一致的。

以这种方式循环异步代理有什么问题吗?

1 个答案:

答案 0 :(得分:0)

我想我明白了。 https://msdn.microsoft.com/en-us/library/dd728068(v=vs.120).aspx &#34;与unbounded_buffer对象不同,receive函数不会从overwrite_buffer对象中删除该消息。如果消费者在生产者覆盖该消息之前多次从消息缓冲区中读取消息,则接收者每次都会获得相同的消息。&#34;