【发布时间】:2015-03-11 16:07:56
【问题描述】:
我的应用程序所做的其中一件事是侦听和接收来自套接字的有效负载。我从不想阻止。在收到的每个有效负载上,我想创建一个对象并将其传递给工作线程,直到稍后再忘记它,这就是原型代码的工作方式。但是对于生产代码,我想通过使用方便的异步方法来降低复杂性(我的应用程序很大)。 async 接受一个由承诺创造的未来。为此,我需要在下面由 Xxx 类表示的非 POD 对象上创建一个 Promise。我没有看到任何方法可以做到这一点(请参阅下面的示例代码中的错误)。在这里使用异步是否合适?如果是这样,我如何构造一个比 int 更复杂的 promise/future 对象(我看到的所有代码示例都使用 int 或 void):
#include <future>
class Xxx //non-POD object
{
int i;
public:
Xxx( int i ) : i( i ) {}
int GetSquare() { return i * i; }
};
int factorial( std::future< Xxx > f )
{
int res = 1;
auto xxx = f.get();
for( int i = xxx.GetSquare(); i > 1; i-- )
{
res *= i;
}
return res;
}
int _tmain( int argc, _TCHAR* argv[] )
{
Xxx xxx( 2 ); // 2 represents one payload from the socket
std::promise< Xxx > p; // error: no appropriate default constructor available
std::future< Xxx > f = p.get_future();
std::future< int > fu = std::async( factorial, std::move( f ) );
p.set_value( xxx );
fu.wait();
return 0;
}
【问题讨论】:
-
你试过给
Xxx一个默认的ctor吗? -
为什么不直接将
xxx传递给异步函数呢?你真的需要双向future通信吗?这只是意味着两个线程都在等待对方。 -
我明白了。由于我已经拥有有效负载数据,因此无需对其做出承诺/未来。只需将 asnyc 的 _Fty&& _Fnarg、_ArgTypes&&... _Args 构造函数与我的复杂参数一起使用。
-
对。您使用
future将结果返回 out ofasync,但您不需要使用一个来传递任何内容。
标签: c++ asynchronous promise