LoginSignup
3
2

More than 1 year has passed since last update.

UEのマルチスレッド処理(C++)

Last updated at Posted at 2022-11-28

今回の方法は、こちらのYouTubeを参考にしました。

準備

Unreal EngineとVisual Studioのインストール
セットアップは下記のURLを参考にしてください。

方法

Step 1 新規C++クラス

o01.PNG
以下の二つクラスを作成します。(UE5バージョン)

  • BlueprintFunctionLibrary
  • Unreal Interface(アンリアル インターフェース)
    o02.PNG

SourceフォルダにMyInterface.cpp、MyInterface.hとMyBlueFunctionLibrary.cpp、MyBlueFunctionLibrary.hが生成してくれます。(名前はデフォルトです。)

Step 2 ヘッダファイル(.hファイル)の編集

MyInterface.h
MyInterface.hのIMyInterfaceクラス内には一つの関数を作ります。

MyInterface.h
public:
	UFUNCTION(BlueprintCallable, BlueprintImplementableEvent, Category = "Multithreaded")
        // イベント名
		void MultithreadFunction();

この関数MultithreadFunctionはバックグラウンド処理を行うタイミングです。
UEではEventというものです。

MyBlueFunctionLibrary.h
MyBlueFunctionLibrary.hのUMyBlueprintFunctionLibraryクラス内には一つの関数を作ります。

MyBlueFunctionLibrary.h
public:
	UFUNCTION(BlueprintCallable, Category = "MyInterface")
        // 非同期処理を呼び関数
		static void CallMultithreadFunction(UObject* object) {
        // 非同期処理のタスクをバックグラウンドで実行
		(new FAutoDeleteAsyncTask<MultithreadedTask>(object))->StartBackgroundTask();
	}

この関数CallMultithreadFunctionはマルチスレッド処理を開始する関数です。
この関数を実行すると、MyInterfaceのMultithreadFunction関数を実行して、
バックグラウンド処理が始まり、マルチスレッドができます。

MyBlueFunctionLibrary.hにはMultithreadedTaskクラスの定義も記述します。
このクラス内にはDoWork関数はMyInterfaceのMultithreadFunction関数を実行するという意味です。

MyBlueFunctionLibrary.h
// このMultithreadedTaskクラスはタスクを定義するクラスです。

class MultithreadedTask : public FNonAbandonableTask {

public:
	UObject* object;

	MultithreadedTask(UObject* object) { this->object = object; }
    // ワーク実行
	// 非同期処理を指定された関数の実行
    void DoWork()
	{
		IMyInterface::Execute_MultithreadFunction(object);
	}

	FORCEINLINE TStatId GetStatId() const
	{
		RETURN_QUICK_DECLARE_CYCLE_STAT(MultithreadedTask, STATGROUP_ThreadPoolAsyncTasks);
	}
};

MyBlueFunctionLibrary.hの先頭のinclude部分にも
マルチスレッド処理用のAsync/AsyncWork.hMyInterface.hをインポートしなければなりません。

MyBlueFunctionLibrary.h
#include "MyInterface.h"
#include "Async/AsyncWork.h"

Step 3 ブループリントで使う

まずはクラス設定のインターフェースでMyInterfaceを追加します。
o04.PNG
o03.PNG

ブループリントでマルチスレッド処理をしたい頃ではCallMultithreadFunctionのノードと連結し、
バックグラウンドで処理したい部分はMultithreadFunctionと連結します。
無題3.png

感想

今回のマルチスレッド処理はAsyncTaskのFAutoDeleteAsyncTaskクラスを使用しました。これはUEから提供しているFQueuedThreadPoolスレッドプールを使用して、タスクが完了したら、自動的にスレッドを削除することができました。
ただし、このスレッドではオブジェクトやアクターの変更ができません。

この方法以外ではFAsyncTaskというクラスもあります。自分のスレッドプールが作れて、削除のタイミングも定義できます。
マルチスレッド処理はまだ初心者なので、今後も学習すべきことがたくさんあると思います。

3DCGシステムのご検討やご相談は弊社までお問い合わせください。

3
2
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
3
2