同步和异步api

Synchronous and ASynchronous APIs

本文关键字:api 异步 同步      更新时间:2023-10-16

我正在开发一个库,它提供一些耗时的服务。我需要每个API的两个版本,一个用于同步函数调用,另一个用于异步。

库用户应该决定使用哪个版本,服务结果可能对系统操作(同步调用)的继续至关重要。同样的操作可能需要在不同的工作线程中完成,因为它的结果不需要继续(异步调用)。

这种方法的问题是什么?

有更好的方法吗?

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

下面是我将要提供的一个示例:

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。'提到,在我的服务中,我需要异步的延续传递样式(API完成后回调)。

您可能想要考虑只提供同步操作,并建议用户使用std::future<...>(或类似的工具,如果您不能使用c++ 2011),如果他们想要异步版本的调用!

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