C++11なコードをとりあえず書いてみただけの記事 †
仕事じゃまだまだ当分 Visual Studio 2008 を使うことになりそうなので、せめて家ではC++11にも触っていかないと…。
というわけでおもむろにC++11なコードを書いてみる。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
-
-
!
|
-
|
!
|
-
!
|
-
-
!
|
|
|
|
-
!
|
|
-
!
|
-
!
!
|
-
!
|
-
!
|
-
!
|
-
!
|
|
!
| #include <thread>
#include <future>
#include <functional>
#include <random>
#include <iostream>
#include <string>
int main()
{
auto printLine =
[](const std::string& text)
{
std::cout << std::this_thread::get_id() << ": " << text << std::endl;
};
auto asyncFunc =
[&printLine]()
{
auto rand =
std::bind(
std::uniform_int_distribution<int>(1, 10),
std::mt19937(std::random_device()()));
auto sec = rand();
std::this_thread::sleep_for(std::chrono::seconds(sec));
printLine("Hello, C++11 world.");
return sec;
};
auto future = std::async(std::launch::async, std::move(asyncFunc));
printLine("Hello, C++11 world.");
auto sec = future.get();
printLine("Sleep for " + std::to_string(sec) + " seconds.");
return 0;
}
|
無駄にラムダ式を使ってますが、 asyncFunc
みたいな長さの場合はちゃんと関数オブジェクトクラスを定義した方がいいと思います。
書いてみて感じたのは、「std::async
すげぇ!」ってことですね。
スレッド内で例外が起きた場合も future.get()
を呼び出したスレッドに例外を投げてくれるみたいですし。
::_beginthreadex
だとかの環境依存コードを書くしかなかったスレッド処理が一気に身近になった感じです。
ああ、こんな素敵なC++11を早く仕事で使えればいいのに…。