1.runnable线程

一个进程至少有一个线程
对于UE4来说,由于多个模块相互依赖,所以使用多线程会比较麻烦
当有网络需求的时候,通常用多线程
加载loading的时候,通常也用多线程

人宅的教程讲的不太好,他侧重于演示线程能干什么,比如在创建线程的时候传入接口
那么这个线程跑起来,就能调用这个接口的方法
但是他并没有把线程之间的关系,讲的很清楚

TaskInterface.h

  1. // Fill out your copyright notice in the Description page of Project Settings.
  2. #pragma once
  3. #include "CoreMinimal.h"
  4. #include "UObject/Interface.h"
  5. #include "TaskInterface.generated.h"
  6. // This class does not need to be modified.
  7. UINTERFACE(MinimalAPI)
  8. class UTaskInterface : public UInterface
  9. {
  10. GENERATED_BODY()
  11. };
  12. /**
  13. *
  14. */
  15. class CPLUSSTUDY_API ITaskInterface
  16. {
  17. GENERATED_BODY()
  18. virtual void DoWork() {};
  19. // Add interface functions to this class. This is the class that will be inherited to implement this interface.
  20. public:
  21. };
  22. class MyInterface :public ITaskInterface
  23. {
  24. public:
  25. void DoWork()override;
  26. protected:
  27. private:
  28. };

TaskInterface.cpp

  1. // Fill out your copyright notice in the Description page of Project Settings.
  2. #include "TaskInterface.h"
  3. // Add default functionality here for any ITaskInterface functions that are not pure virtual.
  4. void MyInterface::DoWork()
  5. {
  6. UE_LOG(LogTemp, Log, TEXT("gjp_xinnianhao!"));
  7. }

ThreadTask.h

  1. // Fill out your copyright notice in the Description page of Project Settings.
  2. #pragma once
  3. #include "CoreMinimal.h"
  4. #include <HAL/Runnable.h>
  5. #include "TaskInterface.h"
  6. #include <HAL/RunnableThread.h>
  7. /**
  8. *
  9. */
  10. class CPLUSSTUDY_API ThreadTask :public FRunnable
  11. {
  12. public:
  13. ThreadTask();
  14. ~ThreadTask();
  15. uint32 Run();
  16. void CreateThread(MyInterface* m_Interface);
  17. private:
  18. FRunnableThread* Task_Thread;
  19. MyInterface* My_Interface;
  20. };

ThreadTask.cpp

  1. // Fill out your copyright notice in the Description page of Project Settings.
  2. #include "ThreadTask.h"
  3. ThreadTask::ThreadTask()
  4. {
  5. }
  6. ThreadTask::~ThreadTask()
  7. {
  8. }
  9. uint32 ThreadTask::Run()
  10. {
  11. if (Task_Thread)
  12. {
  13. My_Interface->DoWork();
  14. }
  15. return 0;
  16. }
  17. void ThreadTask::CreateThread(MyInterface* m_Interface)
  18. {
  19. My_Interface = m_Interface;
  20. Task_Thread = FRunnableThread::Create(this, TEXT("my thread"), 0, TPri_Normal);
  21. }

GameMode

  1. .h
  2. UCLASS()
  3. class CPLUSSTUDY_API AMyGameModeBase : public AGameModeBase
  4. {
  5. GENERATED_BODY()
  6. protected:
  7. virtual void BeginPlay() override;
  8. virtual void EndPlay(const EEndPlayReason::Type EndPlayReason);
  9. private:
  10. MyInterface* newIf;
  11. ThreadTask* newthread;
  12. };
  13. .CPP
  14. #include "MyGameModeBase.h"
  15. void AMyGameModeBase::BeginPlay()
  16. {
  17. //Super::BeginPlay();
  18. newIf = new MyInterface();
  19. newthread = new ThreadTask();
  20. newthread->CreateThread(newIf);
  21. }
  22. void AMyGameModeBase::EndPlay(const EEndPlayReason::Type EndPlayReason)
  23. {
  24. Super::EndPlay(EndPlayReason);
  25. newIf = nullptr;
  26. delete newthread;
  27. }

2.多线程切换

gamemode

  1. // h
  2. #pragma once
  3. #include "CoreMinimal.h"
  4. #include "GameFramework/GameModeBase.h"
  5. #include "ThreadTask.h"
  6. #include "TaskInterface.h"
  7. #include "MyGameModeBase.generated.h"
  8. UCLASS()
  9. class CPLUSSTUDY_API AMyGameModeBase : public AGameModeBase
  10. {
  11. GENERATED_BODY()
  12. protected:
  13. virtual void BeginPlay() override;
  14. virtual void EndPlay(const EEndPlayReason::Type EndPlayReason);
  15. void printt();
  16. private:
  17. MyInterface* newIf;
  18. ThreadTask* newthread;
  19. };
  20. //cpp
  21. #include "MyGameModeBase.h"
  22. void AMyGameModeBase::BeginPlay()
  23. {
  24. //Super::BeginPlay();
  25. AMyGameModeBase* gamebase = nullptr;
  26. newIf = new MyInterface();
  27. newthread = new ThreadTask();
  28. newthread->ThreadTaskDelegate.BindUObject(this, &AMyGameModeBase::printt);
  29. newthread->CreateThread(newIf);
  30. }
  31. void AMyGameModeBase::EndPlay(const EEndPlayReason::Type EndPlayReason)
  32. {
  33. Super::EndPlay(EndPlayReason);
  34. newIf = nullptr;
  35. delete newthread;
  36. }
  37. //主线程执行内容
  38. void AMyGameModeBase::printt()
  39. {
  40. UE_LOG(LogTemp, Log, TEXT("qiehuan_xiancheng")); //断点,在这里的时候切换为主线程
  41. }

ThreadTask

  1. //h
  2. #pragma once
  3. #include "CoreMinimal.h"
  4. #include <HAL/Runnable.h>
  5. #include "TaskInterface.h"
  6. #include <HAL/RunnableThread.h>
  7. DECLARE_DELEGATE(FThreadTask);
  8. class CPLUSSTUDY_API ThreadTask :public FRunnable
  9. {
  10. public:
  11. FThreadTask ThreadTaskDelegate;
  12. ThreadTask();
  13. ~ThreadTask();
  14. uint32 Run();
  15. void CreateThread(MyInterface* m_Interface);
  16. private:
  17. FRunnableThread* Task_Thread;
  18. MyInterface* My_Interface;
  19. };
  20. // cpp
  21. #include "ThreadTask.h"
  22. ThreadTask::ThreadTask()
  23. {
  24. }
  25. ThreadTask::~ThreadTask()
  26. {
  27. }
  28. uint32 ThreadTask::Run()
  29. {
  30. UE_LOG(LogTemp, Log, TEXT("run"));
  31. if (Task_Thread)
  32. {
  33. My_Interface->DoWork();
  34. FGraphEventRef Task = FFunctionGraphTask::CreateAndDispatchWhenReady([&]()
  35. {ThreadTaskDelegate.ExecuteIfBound(); }, TStatId(), nullptr, ENamedThreads::GameThread);//TStatID 方便调试或者解析的工具, null这个位置用来填写执行顺序的先后,这里只有一个task,所以用null
  36. FTaskGraphInterface::Get().WaitUntilTaskCompletes(Task);//等待任务完成
  37. }
  38. return 0;
  39. }
  40. void ThreadTask::CreateThread(MyInterface* m_Interface)
  41. {
  42. My_Interface = m_Interface;
  43. Task_Thread = FRunnableThread::Create(this, TEXT("my thread"), 0, TPri_Normal); //创建线程这一步,好像就已经进入到新线程中
  44. }

TaskInterface

  1. // h
  2. #pragma once
  3. #include "CoreMinimal.h"
  4. #include "UObject/Interface.h"
  5. #include "TaskInterface.generated.h"
  6. // This class does not need to be modified.
  7. UINTERFACE(MinimalAPI)
  8. class UTaskInterface : public UInterface
  9. {
  10. GENERATED_BODY()
  11. };
  12. class CPLUSSTUDY_API ITaskInterface
  13. {
  14. GENERATED_BODY()
  15. virtual void DoWork() {};
  16. // Add interface functions to this class. This is the class that will be inherited to implement this interface.
  17. public:
  18. };
  19. class MyInterface :public ITaskInterface
  20. {
  21. public:
  22. void DoWork()override;
  23. protected:
  24. private:
  25. };
  26. //cpp
  27. #include "TaskInterface.h"
  28. // Add default functionality here for any ITaskInterface functions that are not pure virtual.
  29. void MyInterface::DoWork()
  30. {
  31. UE_LOG(LogTemp, Log, TEXT("gjp_xinnianhao!"));
  32. }

3.使用UE4的闲置线程,GraphTask

//如果要使用UE4的闲置线程,可以使用GraphTask
//创建原生C++,需要提供四个接口,和模板一一匹配

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"

//如果要使用UE4的闲置线程,可以使用GraphTask
//创建原生C++,需要提供四个接口,和模板一一匹配

class FTaskGraph
{
public:
    FTaskGraph(float bb)
        :aa(bb)
    {

    }
    static ESubsequentsMode::Type GetSubsequentsMode() //返回ftaskgraph这个类属于什么类型
    {
        return ESubsequentsMode::TrackSubsequents;
    }
    FORCEINLINE TStatId GetStatId()//返回该事件的类型
    {
        RETURN_QUICK_DECLARE_CYCLE_STAT(FTaskGraph, STATGROUP_TaskGraphTasks);
    }
    void DoTask(ENamedThreads::Type CurrentThread, FGraphEventRef Subsequents)
    {
        UE_LOG(LogTemp, Log, TEXT("helloaaaaaa"),aa);
    }
    static ENamedThreads::Type GetDesiredThread()
    {
        return ENamedThreads::AnyThread;
    }
protected:
private:
    float aa;
};
void AMyGameModeBase::BeginPlay()
{
    //Super::BeginPlay();
    AMyGameModeBase*  gamebase = nullptr;

    TGraphTask<FTaskGraph>::CreateTask(NULL, ENamedThreads::GameThread).ConstructAndDispatchWhenReady(4.5f);
}

4.AsynTask

好像有问题, 有时候不完成任务

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"

class TaskAsync :public FNonAbandonableTask
{

    friend class FAsyncTask<TaskAsync>;
    int32 instanceInt;

    TaskAsync(int32 _instanceInt)
        :instanceInt(_instanceInt)
    {}

    void DoWork()
    {

        UE_LOG(LogTemp, Log, TEXT("dowork_Async %d"), instanceInt);
    }

    FORCEINLINE TStatId GetStatId()const
    {
        RETURN_QUICK_DECLARE_CYCLE_STAT(TaskAsync, STATGROUP_ThreadPoolAsyncTasks);
    }
};
// Fill out your copyright notice in the Description page of Project Settings.


#include "MyGameModeBase.h"
#include <GraphTask.h>
#include <MyAsynTask.h>


void AMyGameModeBase::BeginPlay()
{
    //Super::BeginPlay();
    AMyGameModeBase* gamebase = nullptr;

    FAsyncTask<TaskAsync>* myAsyncTask = new FAsyncTask<TaskAsync>(3);//需要new一个
    myAsyncTask->StartBackgroundTask(); //用后台的线程
    //myAsyncTask->StartSynchronousTask();//依赖顺序的,需要先完成某任务再执行此操作,在游戏线程执行

    if (myAsyncTask->IsDone())
    {
        UE_LOG(LogTemp,Log,TEXT("myAsyncTaskIsDone"));
    }
    myAsyncTask->EnsureCompletion();  //确保完成任务
    delete myAsyncTask;            //以上关于AsyncTask的基本都是固定操作,套路
}

5.三者的区别

Runnable 可用于复杂计算,真正意义上的创建线程,放一些比较重要的任务,比如访问数据库,向服务器发送信息,与网络相关的内容等等

GraphTask 简单的计算,会影响游戏主进程,但支持任务顺序(可以先执行完一些task,再执行自己)

AsyncTask 可用于复杂计算,会从线程池中调用线程,是提前被创建好的

AsyncTask(ENamedThread::GameThread,[&]()
          {UE_LOG(LogTemp,Log,TEXT("aaaa"));}    
         );

很重要:SpawnActor NewObject DestoryUobect /Actor DrawDebugline 这些操作只能在主线程做,不然会触发断言