using nlib_ns::threading::Future;
using nlib_ns::threading::Promise;
using nlib_ns::threading::PackagedTask;
using nlib_ns::threading::Thread;
using nlib_ns::threading::ThreadSettings;
using nlib_ns::threading::ThreadArg;
static int DeferredPlus(int x, int y) {
return x + y;
}
static int Square(Future<int>& x) {
int tmp = x.Get();
return tmp * tmp;
}
bool UsePackagedTask() {
PackagedTask<int(int, int)> task;
Future<int> future;
return false;
} else {
Thread th;
ThreadSettings settings;
settings.SetDetachState(true);
int val1 = 1;
int val2 = 2;
return false;
}
nlib_printf(
"Start PackagedTask{ sleep(2000msec); return x(1) + y(2); }\n");
int result = future.Get();
return true;
}
bool UseAsync() {
Future<int> future;
nlib_printf(
"Start Async{ sleep(2000msec); return x(2) + y(3); }\n");
int result = future.Get();
return true;
}
void CreateData(UniquePtr<ThreadArg<Promise<UniquePtr<int[]> > > >& ptr) {
" Another thread allocates memory and sets data,\n"
" then returns the memory to the main thread.\n");
UniquePtr<int[]> data(new int[1024]);
for (int i = 0; i < 1024; ++i) {
data[i] = i;
}
errno_t e = ptr->arg1.SetValue(data.release());
NLIB_UNUSED(e);
NLIB_ASSERT_NOERR(e);
}
bool UsePromiseAndFuture() {
ThreadArg<Promise<UniquePtr<int[]> > >::ArgType p(new ThreadArg<Promise<UniquePtr<int[]> > >());
Future<UniquePtr<int[]> > myfuture;
p->arg1.GetFuture(&myfuture);
p->func = CreateData;
{
Thread th;
ThreadSettings settings;
settings.SetDetachState(true);
}
int* ptr = myfuture.Get();
NLIB_ASSERT(ptr);
for (int i = 0; i < 1024; ++i) {
if (ptr[i] != i) return false;
}
return true;
}
bool UseContinuation() {
Future<int> future1;
Future<int> future2;
int result = future2.Get();
nlib_printf(
"x = DefferedPlus(2, 3), Square(x, x) = %d, %d\n", future1.Get(), result);
return true;
}
static bool SampleMain(int, char**) {
return UsePackagedTask() && UseAsync() && UsePromiseAndFuture() && UseContinuation();
}
NLIB_MAINFUNC