Top/Lang/C++/C++11/thread

目次

初めに

std::thread

thread の作成

クラスメンバ関数をスレッド関数にする場合

thread 終了を待機する

thread 終了を待機可能かどうか判定する

thread を手放す

thread の識別

現在の thread の処理を明け渡す

void std::this_thread::yield() noexcept;

現在の thread をスリープする

namespace std {
    namespace this_thread {
        template <class Clock, class Duration>
        void sleep_until( const chrono::time_point<Clock, Duration>& abs_time);
        template <class Rep, class Period>
        void sleep_for(const chrono::duration<Rep, Period>& rel_time);
    }
}

並行実行できる thread の数を取得する

namespace std {
    class thread {
      public:
        static unsigned int hardware_concurrency() noexcept;
    };
}

mutex

namespace std {
    class mutex {
      public:
        void lock();
        bool try_lock();
        void unlock();
    };

    class recursive_mutex {
      public:
        void lock();
        bool try_lock();
        void unlock();
    };
}

std::mutex

std::recursive_mutex

std::timed_mutex

std::timed_recursive_mutex

std::shared_mutex [C++17]

std::shared_timed_mutex [C++14]

リソースのロックを管理する

std::lock_guard

#include <mutex>
{
    std::mutex mtx;
    {
         std::lock_guard<mutex> lk( mtx );  // ここからロックが掛かる
         // 処理...

    }  // lk の有効なスコープを抜け、lk のインスタンスが消滅すると同時にロック解除となる
}

std::unique_lock

複数のリソースをロックする

ロックせずに吐いたアクセスする

スレッドセーフに1度だけ関数を呼び出す

条件変数を使用する

thread をまたいで値や例外を受け渡す

std::promise --- 他のスレッドに渡す値や例外を設定する

std::future --- 他のスレッドからセットされた値や例外を取り出す

非同期処理をする

スレッドローカル変数を使用する


トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS