同步和异步 API

2024-05-04

我正在开发一个库,它提供一些耗时的服务。我需要每个 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;
        }
    }
};

EDIT: 作为“马蒂厄·M”提到,在我的服务中,我需要使用连续传递样式(API 完成后回调)进行异步。


您可能需要考虑提供only同步操作并建议用户使用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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

同步和异步 API 的相关文章

随机推荐