同步和异步api
Synchronous and ASynchronous APIs
我正在开发一个库,它提供一些耗时的服务。我需要每个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
相关文章:
- 用于访问容器<T>数据成员的正确 API
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++MySQL C api用户输入行
- 如何使用 AWS Transcribe C++ API 中的'StartTranscriptionJobRequest'?
- 将std::string传递给WriteConsole API
- EvtExportLogneneneba API正在将远程计算机的事件日志保存到远程PC本身.如何将其保存到主机
- 在gtest.中使用fff.h模拟系统API
- 有没有任务栏API可以立即应用注册表更改
- C++win32 API创建多个类似视口的窗口
- 使用libcurl提交批量url的正确BING Api POST url是什么
- 如何使用适用于 S3 的 AWS 开发工具包 cpp 异步 API?
- 使用boost :: Beast进行CPU重的REST API,我是否应该使用异步或同步方式来实现它们以期望延迟
- 在多个线程中使用提升异步 API
- 将第三方异步 API 与 Cap'n Proto RPC 集成的好方法是什么?
- 设计一个结合同步和异步操作的c++ API
- 在异步API (c++)中,如何保证API在调用回调之前返回
- 将波形加载到内存中,然后使用Win32 API异步播放声音
- 异步事件:已定义链接器错误[Windows Update API]
- 同步和异步api