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

查看:25
本文介绍了同步和 ASynchronous 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

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

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