最終更新日時:
が更新

履歴 編集

class template
<thread>

std::thread::name_hint(C++29)

template <same_as<char> T>
class thread::name_hint {
public:
  constexpr explicit name_hint(basic_string_view<T> n) noexcept; // (1) C++29
  name_hint(name_hint&&) = delete;                               // (2) C++29
  name_hint(const name_hint&) = delete;                          // (3) C++29
};

template <class T>
name_hint(const T*) -> name_hint<T>;           // (4) C++29

template <class T>
name_hint(basic_string<T>) -> name_hint<T>;    // (5) C++29

概要

生成するスレッドの名前を設定するための、スレッド属性 (thread attribute) クラス。

threadまたはjthreadのコンストラクタで、関数オブジェクトより前の引数として渡すことで、デバッグやプラットフォーム固有の表示機構のためにスレッド名を設定する。スレッド名は、GDB・LLDB・Visual Studioなどのデバッガのスレッド一覧や、クラッシュダンプ・プロファイラなどの診断ツールで表示される。

std::jthread t{std::thread::name_hint("Worker"), f, 42};

これはあくまでヒントであり、スレッドの名前付けをサポートしないプラットフォームでは無視される。

  • (1) : 文字列nへの参照(basic_string_view)を保持して構築する
  • (2), (3) : コピーもムーブもできない。コンストラクタ引数として直接渡して使う
  • (4), (5) : 文字列リテラル・ポインタやbasic_stringからテンプレート引数を推論できる

jthreadでは、別名jthread::name_hintとしても使用できる。

備考

  • テンプレートパラメータTは現在charのみが許可される。将来ほかの文字型へ拡張する余地を残すため(ABIを壊さずに拡張できるように)テンプレートとして定義されている
  • 名前の文字列は、Tに関連付けられた文字エンコーディング(charでは通常の文字列リテラルのエンコーディング)として解釈されることが推奨される
  • 実装は、name_hint属性の値をthread/jthreadオブジェクトに保存しないことが推奨される。属性オブジェクトはスレッドの生成後に破棄してよい
  • スレッド名の長さにはプラットフォーム固有の制限がある(Linuxでは15文字+終端など)

#include <thread>
#include <iostream>
#include <pthread.h> // POSIX環境

void work(int n)
{
  // ...
}

int main()
{
  // スレッド名"Worker"を指定してスレッドを生成する
  std::jthread t{std::thread::name_hint("Worker"), work, 42};

  // 標準ライブラリにスレッド名を取得するAPIはないが、
  // ネイティブハンドルを通じてプラットフォームのAPIで取得できる
  char name[16]{};
  pthread_getname_np(t.native_handle(), name, sizeof(name));
  std::cout << name << std::endl;
}

出力例

Worker

バージョン

言語

  • C++29

処理系

関連項目

参照