问题
I am developing a library, which provides some time consuming services. I need to have two versions of each API, one for synchronous function call and the other for asynchronous.
Library user should decide which version to use, a service result might be crucial for continue of system operation (synch call). The same operation might be needed to be done in different worker thread as it result is not needed to continue (asynch call).
What are the problems of this approach?
Is there any better way?
Are there popular libraries which provides both sync/async for the same API (Without using external events or threads) ?
Here is an example of what I am going to provide:
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: As ' Matthieu M.' mentioned, In my service I need asynchronous with Continuation Passing Style (callback after API finish).
回答1:
You might want to consider to provide only the synchronous operation and advise users to use std::future<...>
(or a similar facility if you can't use C++ 2011) if they want an asynchronous version of the call!
std::future<StuffStatus> async(std::async(&MyServiceClass::doSomeLengthyStuff,
&service));
// do other stuff
StuffStatus status = async.get(); // get the result, possibly using a blocking wait
来源:https://stackoverflow.com/questions/14093176/synchronous-and-asynchronous-apis