首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >同步和ASynchronous API

同步和ASynchronous API
EN

Stack Overflow用户
提问于 2012-12-30 18:04:55
回答 1查看 2.8K关注 0票数 4

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

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

这种方法的问题是什么?

还有更好的方法吗?

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

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

代码语言:javascript
复制
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;
        }
    }
};

编辑:As‘Matthieu M.’提到过,在我的服务中,我需要异步的延续传递样式( API完成后的回调)。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-30 18:15:52

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

代码语言:javascript
复制
std::future<StuffStatus> async(std::async(&MyServiceClass::doSomeLengthyStuff,
                                          &service));
// do other stuff
StuffStatus status = async.get(); // get the result, possibly using a blocking wait
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14093176

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档