mirror of
https://github.com/ultimatepp/ultimatepp.git
synced 2026-05-16 14:16:09 -06:00
.tutorial
git-svn-id: svn://ultimatepp.org/upp/trunk@11376 f0d560ea-af0d-0410-9eb7-867de7ffcac7
This commit is contained in:
parent
78f7a0fce5
commit
834ac9bd1d
4 changed files with 80 additions and 4 deletions
48
tutorial/CoreTutorial/Async.cpp
Normal file
48
tutorial/CoreTutorial/Async.cpp
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
#include "Tutorial.h"
|
||||
|
||||
void AsyncTutorial()
|
||||
{
|
||||
/// .`AsyncWork`
|
||||
|
||||
/// `AsyncWork` is `CoWork` based tool that resembles std::future. `AsyncWork` instances
|
||||
/// are created using `Async` function and represent a work that can be done in parallel
|
||||
/// with current thread. `AsyncWork` supports returning values. A call to `AsyncWork::Get`
|
||||
/// makes sure that a work routine was finished and returns the return value (if any):
|
||||
|
||||
auto a = Async([](int n) -> double {
|
||||
double f = 1;
|
||||
for(int i = 2; i <= n; i++)
|
||||
f *= i;
|
||||
return f;
|
||||
}, 100);
|
||||
|
||||
DUMP(a.Get());
|
||||
|
||||
/// Exceptions thrown in Async work are propagated upon call to `Get`:
|
||||
|
||||
auto b = Async([] { throw "error"; });
|
||||
|
||||
try {
|
||||
b.Get();
|
||||
}
|
||||
catch(...) {
|
||||
LOG("Exception has been caught");
|
||||
}
|
||||
|
||||
/// `AsyncWork` instances can be canceled (and are canceled in destructor if Get is not
|
||||
/// called on them):
|
||||
|
||||
{
|
||||
auto c = Async([] {
|
||||
for(;;)
|
||||
if(CoWork::IsCanceled()) {
|
||||
LOG("Work was canceled");
|
||||
break;
|
||||
}
|
||||
});
|
||||
Sleep(100); // give it chance to start
|
||||
// c destructor cancels the work (can be explicitly canceled by Cancel method too)
|
||||
}
|
||||
|
||||
///
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue