C++11 以降、標準のスレッドライブラリ std::thread が導入されました。
以前は一部のコンパイラで C++11 のコンパイルオプションとして -std=c++11 を使用していました。
g++ -std=c++11 test.cpp
std::thread コンストラクタ
| デフォルトコンストラクタ | thread() noexcept; |
|---|---|
| 初期化コンストラクタ |
template <class Fn, class... Args> explicit thread(Fn&& fn, Args&&... args); |
| コピーコンストラクタ [deleted] | thread(const thread&) = delete; |
| ムーブコンストラクタ | thread(thread&& x) noexcept; |
- デフォルトコンストラクタは空の
std::thread実行オブジェクトを作成します。 - 初期化コンストラクタは、
std::threadオブジェクトを作成し、そのstd::threadオブジェクトは join 可能であり、joinable新しく生成されたスレッドがfn関数を呼び出します。その関数のパラメータはargs与えられます。 - コピーコンストラクタ(無効)は、
std::threadオブジェクトをコピー構築できないことを意味します。 - ムーブコンストラクタ。move コンストラクタ(move セマンティクスは C++11 で新しく導入された概念です。付録を参照)の呼び出しに成功した後、
xいかなるstd::thread実行オブジェクトも表しません。
注意:join 可能な
joinableのstd::threadオブジェクトは破棄される前にメインスレッドによってjoinjoin されるか、または detached に設定するか。detached.
std::thread各種コンストラクタの例は以下のとおりです。
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
void f1(int n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread " << n << " executing\n";
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void f2(int& n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread 2 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int main()
{
int n = 0;
std::thread t1; // t1 is not a thread
std::thread t2(f1, n + 1); // pass by value
std::thread t3(f2, std::ref(n)); // pass by reference
std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread
t2.join();
t4.join();
std::cout << "Final value of n is " << n << '\n';
}
std::thread 代入操作
| ムーブ代入操作 | thread& operator=(thread&& rhs) noexcept; |
|---|---|
| コピー代入操作 [deleted] | thread& operator=(const thread&) = delete; |
- ムーブ代入操作 (1)。現在のオブジェクトが join 可能でない場合、
joinable右辺値参照rhs) をmove代入操作に渡す必要があります。現在のオブジェクトが join 可能な場合は、joinableすると、terminate() が呼び出されてエラーになります。 - コピー代入操作 (2) は無効化されているため、
std::threadオブジェクトをコピー代入できません。
以下の例を見てください:
#include <stdio.h>
#include <stdlib.h>
#include <chrono> // std::chrono::seconds
#include <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::sleep_for
void thread_task(int n) {
std::this_thread::sleep_for(std::chrono::seconds(n));
std::cout << "hello thread "
<< std::this_thread::get_id()
<< " paused " << n << " seconds" << std::endl;
}
int main(int argc, const char *argv[])
{
std::thread threads[5];
std::cout << "Spawning 5 threads...\n";
for (int i = 0; i < 5; i++) {
threads[i] = std::thread(thread_task, i + 1);
}
std::cout << "Done spawning threads! Now wait for them to join\n";
for (auto& t: threads) {
t.join();
}
std::cout << "All threads joined.\n";
return EXIT_SUCCESS;
}
その他のメンバ関数
get_id: スレッド ID を取得し、std::thread::id 型のオブジェクトを返します。以下の例を見てください:
#include <iostream>
#include <thread>
#include <chrono>
void foo()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
}
int main()
{
std::thread t1(foo);
std::thread::id t1_id = t1.get_id();
std::thread t2(foo);
std::thread::id t2_id = t2.get_id();
std::cout << "t1's id: " << t1_id << '\n';
std::cout << "t2's id: " << t2_id << '\n';
t1.join();
t2.join();
}
joinable: スレッドが join 可能かどうかを確認します。現在のスレッドオブジェクトがアクティブな実行スレッドを表しているかどうかを確認します。デフォルトコンストラクタで作成されたスレッドは join できません。また、あるスレッドがタスクを実行し終えたが join されていない場合、そのスレッドは依然としてアクティブな実行スレッドとみなされるため、join 可能です。
#include <iostream>
#include <thread>
#include <chrono>
void foo()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
}
int main()
{
std::thread t;
std::cout << "before starting, joinable: " << t.joinable() << '\n';
t = std::thread(foo);
std::cout << "after starting, joinable: " << t.joinable() << '\n';
t.join();
}
join: Join 线程,调用该函数会阻塞当前线程,直到由 *this 所标示的线程执行完毕 join 才返回。
#include <iostream>
#include <thread>
#include <chrono>
void foo()
{
// simulate expensive operation
std::this_thread::sleep_for(std::chrono::seconds(1));
}
void bar()
{
// simulate expensive operation
std::this_thread::sleep_for(std::chrono::seconds(1));
}
int main()
{
std::cout << "starting first helper...\n";
std::thread helper1(foo);
std::cout << "starting second helper...\n";
std::thread helper2(bar);
std::cout << "waiting for helpers to finish..." << std::endl;
helper1.join();
helper2.join();
std::cout << "done!\n";
}
detach: スレッドをデタッチします。現在のスレッドオブジェクトが表す実行インスタンスをそのスレッドオブジェクトから分離し、スレッドの実行を単独で行えるようにします。スレッドの実行が完了すると、割り当てられたリソースは解放されます。
detach 関数を呼び出した後:
*thisいかなるスレッド実行インスタンスも表さなくなります。- joinable() == false
- get_id() == std::thread::id()
また、エラーが発生した場合、または joinable() == false の場合は、std::system_error がスローされます。
#include <iostream>
#include <chrono>
#include <thread>
void independentThread()
{
std::cout << "Starting concurrent thread.\n";
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Exiting concurrent thread.\n";
}
void threadCaller()
{
std::cout << "Starting thread caller.\n";
std::thread t(independentThread);
t.detach();
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Exiting thread caller.\n";
}
int main()
{
threadCaller();
std::this_thread::sleep_for(std::chrono::seconds(5));
}
swap: スレッドをスワップします。2つのスレッドオブジェクトが表す基盤となるハンドル(underlying handles)を交換します。
#include <iostream>
#include <thread>
#include <chrono>
void foo()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
}
void bar()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
}
int main()
{
std::thread t1(foo);
std::thread t2(bar);
std::cout << "thread 1 id: " << t1.get_id() << std::endl;
std::cout << "thread 2 id: " << t2.get_id() << std::endl;
std::swap(t1, t2);
std::cout << "after std::swap(t1, t2):" << std::endl;
std::cout << "thread 1 id: " << t1.get_id() << std::endl;
std::cout << "thread 2 id: " << t2.get_id() << std::endl;
t1.swap(t2);
std::cout << "after t1.swap(t2):" << std::endl;
std::cout << "thread 1 id: " << t1.get_id() << std::endl;
std::cout << "thread 2 id: " << t2.get_id() << std::endl;
t1.join();
t2.join();
}
実行結果は以下のとおりです:
thread 1 id: 1892 thread 2 id: 2584 after std::swap(t1, t2): thread 1 id: 2584 thread 2 id: 1892 after t1.swap(t2): thread 1 id: 1892 thread 2 id: 2584
native_handle: native handle を返します(std::thread の実装はオペレーティングシステムに依存するため、この関数は std::thread の具体的な実装に関連するスレッドハンドルを返します。例えば、Posix 標準に準拠したプラットフォーム(Unix/Linux など)では Pthread ライブラリです)。
#include <thread>
#include <iostream>
#include <chrono>
#include <cstring>
#include <pthread.h>
std::mutex iomutex;
void f(int num)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
sched_param sch;
int policy;
pthread_getschedparam(pthread_self(), &policy, &sch);
std::lock_guard<std::mutex> lk(iomutex);
std::cout << "Thread " << num << " is executing at priority "
<< sch.sched_priority << '\n';
}
int main()
{
std::thread t1(f, 1), t2(f, 2);
sched_param sch;
int policy;
pthread_getschedparam(t1.native_handle(), &policy, &sch);
sch.sched_priority = 20;
if(pthread_setschedparam(t1.native_handle(), SCHED_FIFO, &sch)) {
std::cout << "Failed to setschedparam: " << std::strerror(errno) << '\n';
}
t1.join();
t2.join();
}
実行結果は以下のとおりです:
Thread 2 is executing at priority 0 Thread 1 is executing at priority 20
hardware_concurrency [static]: ハードウェアの並行性を検出し、現在のプラットフォームのスレッド実装がサポートするスレッド並行数を返します。ただし、戻り値はシステムのヒント(hint)としてのみ提供されます。
#include <iostream>
#include <thread>
int main() {
unsigned int n = std::thread::hardware_concurrency();
std::cout << n << " concurrent threads are supported.\n";
}
std::this_thread 名前空間内の関連ヘルパー関数の紹介
get_id: スレッド ID を取得します。
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
std::mutex g_display_mutex;
void foo()
{
std::thread::id this_id = std::this_thread::get_id();
g_display_mutex.lock();
std::cout << "thread " << this_id << " sleeping...\n";
g_display_mutex.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
int main()
{
std::thread t1(foo);
std::thread t2(foo);
t1.join();
t2.join();
}
yield: 現在のスレッドは実行を放棄し、オペレーティングシステムが別のスレッドをスケジュールして実行を継続します。
#include <iostream>
#include <chrono>
#include <thread>
// "busy sleep" while suggesting that other threads run
// for a small amount of time
void little_sleep(std::chrono::microseconds us)
{
auto start = std::chrono::high_resolution_clock::now();
auto end = start + us;
do {
std::this_thread::yield();
} while (std::chrono::high_resolution_clock::now() < end);
}
int main()
{
auto start = std::chrono::high_resolution_clock::now();
little_sleep(std::chrono::microseconds(100));
auto elapsed = std::chrono::high_resolution_clock::now() - start;
std::cout << "waited for "
<< std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count()
<< " microseconds\n";
}
sleep_until: スレッドは指定された時点(time point)まで休眠し、その時点で再び起こされます。
template< class Clock, class Duration > void sleep_until( const std::chrono::time_point<Clock,Duration>& sleep_time );
sleep_for: スレッドは指定された時間(time span)だけ休眠し、その時間が経過すると再び起こされます。ただし、スレッドスケジューリングなどの理由により、実際の休眠時間は sleep_duration で表される時間よりも長くなる可能性があります。
#include <iostream>
#include <chrono>
#include <thread>
int main()
{
std::cout << "Hello waiter" << std::endl;
std::chrono::milliseconds dura( 2000 );
std::this_thread::sleep_for( dura );
std::cout << "Waited 2000 ms\n";
}
実行結果は以下のとおりです:
Hello waiter Waited 2000 ms
出典:https://github.com/forhappy/Cplusplus-Concurrency-In-Practice/blob/master/zh/chapter3-Thread/Introduction-to-Thread.md