在UE4中创建多线程

以下参考链接:https://wiki.unrealengine.com/index.php?title=Multi-Threading:_How_to_Create_Threads_in_UE4

以下是如何在UE4中创建线程,主要实现了:
  • 创建一个线程来计算前50000个素数。
  • 把计算完成的数据发送给主线程
  • 静态函数,用于启动、关闭、查找线程是否已经完成。
    这虽然是一个可行的方案,但是在创建许多任务时,可能会达到CPU可以处理的并发上限,此时并发线程实际上会在争用CPU时间时相互阻碍。FQueuedThreadPool可以限制任务可用的线程数。
    .h
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"

/**
 * 
 */
class THREADPROJECT_API FPrimeNumberWorker : public FRunnable
{
    /** Singleton instance, can access the thread any time via static accessor, if it is active! */
    static  FPrimeNumberWorker* Runnable;

    /** Thread to run the worker FRunnable on */
    FRunnableThread* Thread;

    /** The Data Ptr */
    TArray* PrimeNumbers;

    /** The PC */
    class AVictoryGamePlayerController* ThePC;

    /** Stop this thread? Uses Thread Safe Counter */
    FThreadSafeCounter StopTaskCounter;

    //The actual finding of prime numbers
    int32 FindNextPrimeNumber();

private:

    int32 PrimesFoundCount;

public:

    int32 TotalPrimesToFind;

    //判断是否完成
    bool IsFinished() const
    {
        return PrimesFoundCount >= TotalPrimesToFind;
    }

    //~~~ Thread Core Functions ~~~

    //Constructor / Destructor
    FPrimeNumberWorker( TArray& TheArray , const int32 IN_PrimesToFindPerTick ,class AVictoryGamePlayerController* IN_PC );
    virtual ~FPrimeNumberWorker();

    // Begin FRunnable interface.
    virtual bool Init();
    virtual uint32 Run();
    virtual void Stop();
    // End FRunnable interface

    /** 确保线程被正确的停止 */
    void EnsureCompletion();



    //~~~ 开启,停止线程~~~



    /*
        Start the thread and the worker from static (easy access)!
        确保当前只有一个 thread实例在运行.
        This function returns a handle to the newly started instance.
    */
    static FPrimeNumberWorker* JoyInit( TArray& TheArray , const int32 IN_TotalPrimesToFind , AVictoryGamePlayerController* IN_PC );

    /** 关闭线程,静态函数可以方便在外面调用*/

    static void Shutdown();

    static bool IsThreadFinished();

    
    
    
    
};

.cpp

#include "FPrimeNumberWorker.h"
#include "ThreadingBase.h"
#include "VictoryGamePlayerController.h"


//***********************************************************
//Thread Worker Starts as NULL, prior to being instanced
//      This line is essential! Compiler error without it
FPrimeNumberWorker* FPrimeNumberWorker::Runnable = NULL;
//***********************************************************

FPrimeNumberWorker::FPrimeNumberWorker( TArray& TheArray , const int32 IN_TotalPrimesToFind , AVictoryGamePlayerController* IN_PC )
    : ThePC( IN_PC ),
    TotalPrimesToFind( IN_TotalPrimesToFind )
    , StopTaskCounter( 0 )
    , PrimesFoundCount( 0 )
{
    //Link to where data should be stored
    PrimeNumbers = &TheArray;

    Thread = FRunnableThread::Create( this , TEXT( "FPrimeNumberWorker" ) , 0 , TPri_BelowNormal ); //windows default = 8mb for thread, could specify more
}

FPrimeNumberWorker::~FPrimeNumberWorker()
{
    delete Thread;
    Thread = NULL;
}

//Init
bool FPrimeNumberWorker::Init()
{
    //Init the Data 
    PrimeNumbers->Empty();
    PrimeNumbers->Add( 2 );
    PrimeNumbers->Add( 3 );

    if( ThePC )
    {
        ThePC->ClientMessage( "**********************************" );
        ThePC->ClientMessage( "Prime Number Thread Started!" );
        ThePC->ClientMessage( "**********************************" );
    }
    return true;
}

//Run
uint32 FPrimeNumberWorker::Run()
{
    //Initial wait before starting
    FPlatformProcess::Sleep( 0.03 );

    //确保没有手动停止线程
    //      and 查找没有完成
    while( StopTaskCounter.GetValue() == 0 && !IsFinished() )
    {
        PrimeNumbers->Add( FindNextPrimeNumber() );
        PrimesFoundCount++;

        //***************************************
        //Show Incremental Results in Main Game Thread!

        //  Please note you should not create, destroy, or modify UObjects here.
        //    Do those sort of things after all thread are completed.

        //    All calcs for making stuff can be done in the threads
        //       But the actual making/modifying of the UObjects should be done in main game thread.

        ThePC->ClientMessage( FString::FromInt( PrimeNumbers->Last() ) );

        //***************************************

        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        //prevent thread from using too many resources
        //FPlatformProcess::Sleep(0.01);
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    }

    //Run FPrimeNumberWorker::Shutdown() from the timer in Game Thread that is watching
        //to see when FPrimeNumberWorker::IsThreadFinished()

    return 0;
}

//stop
void FPrimeNumberWorker::Stop()
{
    StopTaskCounter.Increment();
}

FPrimeNumberWorker* FPrimeNumberWorker::JoyInit( TArray& TheArray , const int32 IN_TotalPrimesToFind , AVictoryGamePlayerController* IN_PC )
{
    //Create new instance of thread if it does not exist
    //      and the platform supports multi threading!
    if( !Runnable && FPlatformProcess::SupportsMultithreading() )
    {
        Runnable = new FPrimeNumberWorker( TheArray , IN_TotalPrimesToFind , IN_PC );
    }
    return Runnable;
}

void FPrimeNumberWorker::EnsureCompletion()
{
    Stop();
    Thread->WaitForCompletion();
}

void FPrimeNumberWorker::Shutdown()
{
    if( Runnable )
    {
        Runnable->EnsureCompletion();
        delete Runnable;
        Runnable = NULL;
    }
}

bool FPrimeNumberWorker::IsThreadFinished()
{
    if( Runnable ) return Runnable->IsFinished();
    return true;
}
int32 FPrimeNumberWorker::FindNextPrimeNumber()
{
    //Last known prime number  + 1
    int32 TestPrime = PrimeNumbers->Last();

    bool NumIsPrime = false;
    while( !NumIsPrime )
    {
        NumIsPrime = true;

        //Try Next Number
        TestPrime++;

        //Modulus from 2 to current number - 1 
        for( int32 b = 2; b < TestPrime; b++ )
        {
            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            //prevent thread from using too many resources
            //FPlatformProcess::Sleep(0.01);
            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            if( TestPrime % b == 0 )
            {
                NumIsPrime = false;
                break;
                //~~~
            }
        }
    }

    //Success!
    return TestPrime;
}

需要创建线程时在可以在playerController里直接调用静态函数JoyInit,停止调用shutDown。

你可能感兴趣的:(在UE4中创建多线程)