nlib
misc/threading/threadpool/threadpool.cpp

This is a thread pool sample. Using a thread pool allows for a different thread to calculate without the overhead of starting a thread.

/*---------------------------------------------------------------------------*
Project: CrossRoad
Copyright (C)2012-2016 Nintendo. All rights reserved.
These coded instructions, statements, and computer programs contain
proprietary information of Nintendo of America Inc. and/or Nintendo
Company Ltd., and are protected by Federal copyright law. They may
not be disclosed to third parties or copied or duplicated in any form,
in whole or in part, without the prior written consent of Nintendo.
*---------------------------------------------------------------------------*/
#include "nn/nlib/Swap.h"
using nlib_ns::threading::ThreadPool;
using nlib_ns::threading::Future;
int g_Var = 10000;
int TaskFunc() {
int sum = 0;
for (int i = 0; i < g_Var; ++i) {
sum += i;
}
return sum;
}
class FuncObj {
public:
// you have to implement the default constructor and swap member function
FuncObj() : var_(0) {}
#ifdef NLIB_CXX11_RVALUE_REFERENCES
FuncObj(FuncObj&& rhs) NLIB_NOEXCEPT : var_(rhs.var_) {}
FuncObj& operator=(FuncObj&& rhs) NLIB_NOEXCEPT {
var_ = rhs.var_;
return *this;
}
#endif
void swap(FuncObj& rhs) NLIB_NOEXCEPT { // NOLINT
using std::swap;
swap(rhs.var_, var_);
}
explicit FuncObj(int v) : var_(v) {}
int operator()() {
int sum = 0;
for (int i = 0; i < var_; ++i) {
sum += i;
}
return sum;
}
private:
int var_;
};
NLIB_DEFINE_STD_SWAP(FuncObj)
static bool SampleMain(int, char**) {
ThreadPool pool;
e = pool.Init();
if (nlib_is_error(e)) return false;
nlib_printf("This sample shows that ThreadPool object can take function, "
"functional object, and lambda as a task.\n\n");
// You can pass functions to ThreadPool
Future<int> future1;
e = pool.Submit(&future1, TaskFunc);
if (nlib_is_error(e)) return false;
// You can also pass functional objects to ThreadPool,
// 'obj' is swapped in Submit() function.
Future<int> future2;
FuncObj obj(10000);
e = pool.Submit(&future2, obj);
if (nlib_is_error(e)) return false;
#ifdef NLIB_CXX11_LAMBDAS
// You can pass lambdas to ThreadPool on C++11.
// but you should use a temporary variable for lambda,
// otherwise the compliler may generate warnings.
Future<int> future3;
int var;
auto lambdaFunc = [&var]() {
int sum = 0;
for (int i = 0; i < var; ++i) {
sum += i;
}
return sum;
};
var = 10000;
e = pool.Submit(&future3, lambdaFunc);
if (nlib_is_error(e)) return false;
#endif
int sum1;
e = future1.Get(&sum1);
if (nlib_is_error(e)) return false;
nlib_printf("TaskFunc(function): SUM[0, %d) = %d\n", g_Var, sum1);
int sum2;
e = future2.Get(&sum2);
if (nlib_is_error(e)) return false;
nlib_printf("FuncObj(functional object): SUM[0, 10000) = %d\n", sum2);
#ifdef NLIB_CXX11_LAMBDAS
int sum3;
e = future3.Get(&sum3);
if (nlib_is_error(e)) return false;
nlib_printf("lambdaFunc(lambda): SUM[0, %d) = %d\n", var, sum3);
#endif
return true;
}
NLIB_MAINFUNC