同步和异步API [英] Synchronous and ASynchronous APIs

查看:232
本文介绍了同步和异步API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个图书馆,该图书馆提供一些耗时的服务.我需要每个API有两个版本,一个用于同步函数调用,另一个用于异步.

I am developing a library, which provides some time consuming services. I need to have two versions of each API, one for synchronous function call and the other for asynchronous.

图书馆用户应决定使用哪个版本,服务结果对于继续系统操作(同步调用)可能至关重要.可能需要在不同的工作线程中执行相同的操作,因为不需要继续执行此结果(异步调用).

Library user should decide which version to use, a service result might be crucial for continue of system operation (synch call). The same operation might be needed to be done in different worker thread as it result is not needed to continue (asynch call).

此方法有什么问题?

还有更好的方法吗?

是否有流行的库为同一个API提供同步/异步功能(不使用外部事件或线程)?

以下是我要提供的示例:

Here is an example of what I am going to provide:

enum StuffStatus
{
    SUCCEED,
    FAILED,
    STILL_RUNNING
};
class IServiceCallback
{
public:
    void lengthyStuffCallback(StuffStatus status);
};

class MyServiceClass
{
public:
    StuffStatus doSomeLengthStuff(IServiceCallback* callback)
    {
        if( callback == NULL ) // user wants sync. call
        {
            // do all operations in caller context
            return SUCCEED;
        }else{
            // save the callback, queue the request in a separate worker thread. 
            // and after the worker thread finishes the job it calls callback->lengthyStuffCallback(SUCCEED) from its context.
            return STILL_RUNNING;
        }
    }
};

编辑: 作为马修·M."提到,在我的服务中,我需要与Continuation Passing Style(API完成后的回调)异步.

EDIT: As ' Matthieu M.' mentioned, In my service I need asynchronous with Continuation Passing Style (callback after API finish).

推荐答案

您可能要考虑仅提供 同步操作,并建议用户使用std::future<...>(如果您使用类似的工具,如果希望使用异步版本的调用,则不能使用C ++ 2011!

You might want to consider to provide only the synchronous operation and advise users to use std::future<...> (or a similar facility if you can't use C++ 2011) if they want an asynchronous version of the call!

std::future<StuffStatus> async(std::async(&MyServiceClass::doSomeLengthyStuff,
                                          &service));
// do other stuff
StuffStatus status = async.get(); // get the result, possibly using a blocking wait

这篇关于同步和异步API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆