2012-09-16 (日)
*future使ってみる
async良い感じ.
#include <iostream> #include <future> using namespace std; int main() { int a[] = { 1, 2, 3, 4, 5, 6, 7 }; auto f1 = async([&]{ long r = 0; for (const auto &n : a) { r += n; cout << "add " << n << endl; std::this_thread::sleep_for(std::chrono::milliseconds(50)); } return r; }); auto f2 = async([&]{ long r = 1; for (const auto &n : a) { r *= n; cout << "mul " << n << endl; std::this_thread::sleep_for(std::chrono::milliseconds(50)); } return r; }); cout << "f1:" << f1.get() << " f2:" << f2.get() << endl; return 0; }
排他処理もstd::mutexあるので良いですね.
しかし,
std::this_thread::sleep_for(std::chrono::milliseconds(50));
これ長すぎる…….