「std::promise」の版間の差分

提供: C++入門
移動: 案内検索
行45: 行45:
 
                 int r = f0.get();                                      // 同期でタスク処理を待つ
 
                 int r = f0.get();                                      // 同期でタスク処理を待つ
 
                 cout << r << endl;                                      // 結果を表示
 
                 cout << r << endl;                                      // 結果を表示
 +
                cout << num << endl;
 
                 t1.join();                                              // スレッドの終了を待つ
 
                 t1.join();                                              // スレッドの終了を待つ
 
         } catch (std::exception& e) {
 
         } catch (std::exception& e) {
行62: 行63:
 
0
 
0
 
execute: int foo(std::promise<int>&, int&)
 
execute: int foo(std::promise<int>&, int&)
 +
10
 
10
 
10
 
</syntaxhighlight>
 
</syntaxhighlight>
行69: 行71:
 
* [[std::promise]]
 
* [[std::promise]]
 
* [[std::packaged_task]]
 
* [[std::packaged_task]]
{{thread}}
+
<!-- vim: filetype=mediawiki
{{mutex}}
+
-->
<!-- vim: filetype=mediawiki -->
+

2015年4月25日 (土) 10:49時点における版

std::promise とは、C++のスレッド用のライブラリです。std::threadstd::futurestd::promiseを使用して、別スレッドの終了を待ち、処理の結果を取得するような非同期処理を実現します。

読み方

std::promise
えすてぃーでぃー ぷろみす

概要

  • 戻り値、または、例外を扱えます。
  • 戻り値の型は、テンプレートで指定します。
  • 例外は、任意の型を扱えます。
  • std::futureは、スレッドの完了を待ちます(同期)。
  • std::fetureオブジェクトは、std::promiseオブジェクトのget_future()で作成します。

std::promisestd::thread で実現する方法と std::async で実現する方法があります。

ヘッダファイル

#include <future>

std::promiseとstd::threadの例

ソースコード std_promise1.cpp

#include <iostream>
#include <future>
#include <thread>
#include <unistd.h>     // sleep
using namespace std;
int
foo (std::promise<int>& pi, int& num) {
        cout << "execute: " << __PRETTY_FUNCTION__ << endl;
        for (int i = 0; i < 10; i++) {
                num++;
                sleep (1);
        }
        pi.set_value(num);
}
int main(int argc, char const* argv[])
{
        try {
                std::promise<int> pi;
                int     num = 0;
                std::thread t1(foo, std::ref(pi), std::ref(num));       // スレッドを開始
                cout << num << endl;
                std::future<int> f0 = pi.get_future();                  // 非同期オブジェクトを受け取る宣言
                int r = f0.get();                                       // 同期でタスク処理を待つ
                cout << r << endl;                                      // 結果を表示
                cout << num << endl;
                t1.join();                                              // スレッドの終了を待つ
        } catch (std::exception& e) {
                cerr << e.what() << endl;
        }
        return 0;
}

コンパイル

g++49 -std=c++11 -I/usr/local/lib/gcc49/include/c++/ \
-Wl,-rpath=/usr/local/lib/gcc49  -pthread std_promise1.cpp -o std_promise1

実行例

% ./std_promise1
0
execute: int foo(std::promise<int>&, int&)
10
10

関連項目