You*_*usf 4 c++ api asynchronous synchronous
我正在开发一个库,它提供了一些耗时的服务.我需要每个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;
}
}
};
Run Code Online (Sandbox Code Playgroud)
编辑:作为'Matthieu M.' 提到,在我的服务中,我需要与Continuation Passing Style异步(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
Run Code Online (Sandbox Code Playgroud)