Concurrent Waiting
Concurrent waiting can be drawn on the basis of these three mechanisms
Concurrent Waiting | .get
size_t
file_sizes( string file1, string file2 )
{
task<file> f1 = open(file1),
f2 = open(file2);
return f1.get().size() +
f2.get().size();
}
Concurrent Waiting | .then
task<size_t>
file_sizes( string file1, string file2 )
{
task<file> f1 = open(file1),
f2 = open(file2);
return when_all(f1,f2)
.then([=](tuple<file,file> fs)
{
return get<1>(fs).size() +
get<2>(fs).size();
});
}
Concurrent Waiting | .then + await
task<size_t>
file_sizes( string file1, string file2 ) __async
{
task<file> f1 = open(file1),
f2 = open(file2);
return (__await f1).size() +
(__await f2).size();
}
Real Payoffs | Branches & Loops
Branches & Loops | .get string
read( string file, string suffix )
{
istream fi = open(file).get();
string ret, chunk;
while( (chunk = fi.read().get()).size() )
ret += chunk + suffix;
return ret;
}
Branches & Loops | .then
task<string>
read( string file, string suffix )
{
return open(file)
.then([=](istream fi)
{
auto ret = make_shared<string>();
auto next =
make_shared<function<task<string>()>>(
[=]
{
fi.read()
.then([=](string chunk)
{
if( chunk.size() )
{
*ret += chunk + suffix;
return (*next)();
}
return *ret;
});
});
return (*next)();
});
}
Branches & Loops | .then + await
task<string>
read( string file, string suffix ) __async
{
istream fi = __await open(file);
string ret, chunk;
while( (chunk = __await fi.read()).size() )
ret += chunk + suffix;
return ret;
}