0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Visual Studio (VC++)で std::thread を使って、メンバ関数でスレッドを立てて、その優先度を変更するサンプルコード

Last updated at Posted at 2020-12-06

こういう情報は、サクッと欲しいですよね。
クラス内でスレッドを立てて、さらにそのスレッドを優先度を上げたり下げたりバックグラウンドで動かしたい時のサンプルです。

ミソは、以下のポイント。
・メンバ変数にスレッドを持っているので、このクラス単体でスレッド管理していること
・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";
}
0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?