2016-12-29 81 views
0

我開始與基本-agents.cpp這裏Asynchronous Agents但我想考出一個循環,所以我做C++異步代理奇怪的行爲

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'響應中出現序列無序接收。這不會發生在其他地方並且一致。

有什麼毛病我以這種方式循環異步代理?

回答

0

我想我得到了它。 https://msdn.microsoft.com/en-us/library/dd728068(v=vs.120).aspx 「不同於與unbounded_buffer對象,接收功能不會從overwrite_buffer對象中刪除該消息。如果消費者從消息緩衝器讀取生產者將覆蓋消息之前一次以上時,接收機獲得相同的消息每次「。