std::async

提供: C++入門
移動: 案内検索
スポンサーリンク

std::async とは、C++11で導入された指定した関数を非同期実行する機能です。

読み方

std::async
えすてぃーでぃー あしんく

概要

std::threadboost::threadを使わずに、簡単な非同期実行を実現できます。

std::asyncによる非同期実行の例

  • 最初のasyncでは、すぐにfooが実行されます。
  • 2つめのasyncでは、遅延実行するため、メインスレッドのsleepが終わったあとに、fooが実行されています。

ソースコード std_async1.cpp

#include <iostream>
#include <future>
#include <thread>
#include <ctime>
using namespace std;
int
foo () {
        cout << "execute: " << __PRETTY_FUNCTION__ << endl;
        return time(NULL);
}
int main(int argc, char const* argv[])
{
        {
                cout << "async foo" << endl;
                future<int> f1 = std::async(
                                std::launch::async, foo);
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
                cout << "after sleep" << endl;
                int r = f1.get();
                cout << r << endl;
        }
        cout << endl;
 
        {
                cout << "async deferred foo" << endl;
                future<int> f1 = std::async(
                                std::launch::deferred, foo);
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
                cout << "after sleep" << endl;
                int r = f1.get();
                cout << r << endl;
        }
        return 0;
}

コンパイル

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

実行例

% ./std_async1
async foo
execute: int foo()
after sleep
1388332617
 
async deferred foo
after sleep
execute: int foo()
1388332617

関連項目

std::thread メンバ関数
関数 説明
メンバ関数
std::thread::thread コンストラクタ。threadオブジェクトを作成します。
std::thread::~thread スレッドがjoinかdetachされている必要があります。スレッドオブジェクトを破棄します。
std::thread::operator= スレッドオブジェクトをmoveします。
オブザーバー
std::thread::joinable スレッドが合流可能であるかチェックします。
std::thread::get_id スレッドのIDを返します。
std::thread::native_handle スレッドハンドルを返します。
std::thread::hardware_concurrency 実装によってサポートされる同時スレッド数を返します。
操作
std::thread::join スレッドの終了を待ちます。
std::thread::detach スレッドハンドルから独立して実行するスレッドを許可します。
std::thread::swap スワップ
非メンバ関数
std::swap スワップ
カレントスレッドの管理
std::this_thread::yield_id 処理系に再スケジュールの機会を与えます。
std::this_thread::get_id スレッドIDを返します。
std::this_thread::sleep_for 指定した時間、現在のスレッドの実行を停止します。
std::this_thread::sleep_until 指定した時刻まで、現在のスレッドの実行を停止します。
mutex
mutexの種類 説明
std::mutex 非再帰的mutex
std::recursive_mutex 再帰的mutext
std::timed_mutex ロック関数でタイムアウトが可能な非再帰的mutex
std::recursive_timed_mutex ロック関数でタイムアウトが可能な再帰的mutex

ロッククラステンプレート





スポンサーリンク