美文网首页
【Poco笔记】Poco中的ActiveMethod和Activ

【Poco笔记】Poco中的ActiveMethod和Activ

作者: 安安爸Chris | 来源:发表于2018-10-18 10:34 被阅读0次

Poco中的ActivieMethod和ActivieResult封装一套异步调用过程,思想与.NET和JAVA类似。其实,在C++11标准中,也引入了异步过程。可以参考如下示例

string send(string msg) {
    this_thread::sleep_for(chrono::milliseconds(2000));
    return "You have sent:  "+msg;
}

int main(int argc, char **argv) {
    cout << "[" << time_str() << "]begin to send message...." << endl;
    string msg = "I love you!";
    future<string> fut = async(send, msg);
    fut.wait();
    cout << "[" << time_str() << "]" << fut.get() << endl;

    return 0;
}
执行结果 c++异步执行.PNG

Poco中使用ActivieMethod和ActivieResult来实现future同样的功能,样例如下

class MessageSender {
public:
    MessageSender() : send_message_method(this, &MessageSender::send) {
    };

    Poco::ActiveMethod<string, string, MessageSender> send_message_method;

private:
    std::string send(const string& msg) {
        this_thread::sleep_for(chrono::milliseconds(2000));
        return "You have sent:  "+msg;
    };
};

int main(int argc, char **argv) {
    cout << "[" << time_str() << "]begin to send message...." << endl;
    MessageSender sender;
    Poco::ActiveResult<string> result = sender.send_message_method("hello world");
    result.wait();
    cout << "[" << time_str() << "]" << result.data() << endl;

    return 0;
}

执行结果


ActiveMehod异步.PNG

有关于wait_for,这里有例子参考http://www.cplusplus.com/reference/future/future/wait_for/
但是我在centos7(g++4.8)上执行并不能正常运行,wait_for的状态始终是timeout. 不知道有没有同样遇到问题的小伙伴。

那么Poco有类似的实现吗? 答案是有的,下面是样例。

// class MessageSender没有改动,省略

int main(int argc, char **argv) {
    cout << "[" << time_str() << "]begin to send message...." << endl;
    MessageSender sender;
    Poco::ActiveResult<string> result = sender.send_message_method("hello world");
    while (!result.available()) {
        result.tryWait(250);
        cout << "." << flush;
    }
    cout << "\n[" << time_str() << "]" << result.data() << endl;

    return 0;
}

Poco的封装更切近与高级语言,使用更加亲切。
运行结果


result.gif

OK.我们来总结一下Poco中的AcitveMethod和ActiveResult与c++11中实现的比较

  1. c++11总async只能面向全局函数,不能面向对象函数。而Poco可以。
    2.对于标准行为来说c++11的各个编译器可能实现不确定,但是Poco较为稳定。

相关文章

网友评论

      本文标题:【Poco笔记】Poco中的ActiveMethod和Activ

      本文链接:https://www.haomeiwen.com/subject/kcljzftx.html