nlib
misc/threading/threadpool/threadpool.cpp

スレッドプールのサンプルです。 スレッドプールを使うと、スレッドの立ち上げコストなしに別スレッドに計算をさせることができます。

/*--------------------------------------------------------------------------------*
Project: CrossRoad
Copyright (C)Nintendo All rights reserved.
These coded instructions, statements, and computer programs contain proprietary
information of Nintendo and/or its licensed developers and are protected by
national and international copyright laws. 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.
The content herein is highly confidential and should be handled accordingly.
*--------------------------------------------------------------------------------*/
#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