こういう情報は、サクッと欲しいですよね。
クラス内でスレッドを立てて、さらにそのスレッドを優先度を上げたり下げたりバックグラウンドで動かしたい時のサンプルです。
ミソは、以下のポイント。
・メンバ変数にスレッドを持っているので、このクラス単体でスレッド管理していること
・std::thread の第2引数に "this" を投げることで、メンバ関数でもスレッド立てられること
・.native_handle() により環境依存のハンドルを取得し、Windowsなら SetThreadPriority() 関数で優先度を変えられること
余談ですが、メンバ変数std::thread th & swap() がダメなら、ポインタメンバ変数std::thread *th & コンストラクタや初期化関数で th = new thread~ でもありだと思います。(その際デストラクタ等で delete を忘れないこと)
なお、こちらの環境はVisual Studio 2017です。
main.cpp
# include <iostream>
# include <Windows.h>
# include "ThreadStart.h"
int main(void) {
ThreadStart tst;
Sleep(2000); // 2秒待つ
std::cout << "bye at main()\n";
return 0;
}
ThreadStart.h
# include <iostream>
# include <string>
# include <thread>
# include <Windows.h>
class ThreadStart
{
public:
ThreadStart();
~ThreadStart();
private:
void newThread();
std::thread m_th;
};
ThreadStart.cpp
# include "ThreadStart.h"
using namespace std;
ThreadStart::ThreadStart()
{
// スレッド起動
thread th(&ThreadStart::newThread, this);
// 優先度を変更
int ret;
ret = SetThreadPriority(
th.native_handle(),
THREAD_PRIORITY_BELOW_NORMAL // 通常以下
);
// エラー表示
if (ret == 0) {
string str;
str = "Failed change priority err:";
str += to_string(GetLastError());
str += "\n";
cout << str;
}
// スレッド管理をメンバ変数に移譲
th.swap(m_th);
}
ThreadStart::~ThreadStart()
{
cout << "bye at thread\n";
m_th.join();
}
void ThreadStart::newThread()
{
cout << "hello thread!\n";
}