Multi-Threading: How to Create Threads in UE4

Weaxor勒索病毒实战分析:从加密算法到防御策略(附检测工具清单) 本文对Weaxor勒索病毒进行了深度实战剖析,详细拆解了其采用ChaCha20与AES-CTR的混合加密算法、横向移动手法及数据回传行为。文章重点分析了其密钥生成机制的“漏洞修复”,并提供了从主机加固、网络监控到基于IOC威胁狩猎的立体化企业级防御策略与检测工具清单。 阅读详情

Overview

Dear Community,

Here is how you can create your own threads in UE4!

This is the code you'd use for a very large task.

For small incremental tasks that can be divided into chunks check out my Task Graph Tutorial:

Multi-Threading:_Task_Graph_System

What The Code Below Does

  • Creates a thread to compute the first 50,000 prime numbers
  • Sends incremental completion data back to the Game Thread
  • Has static accessors for starting, shutting down, and finding out if thread is done.

Static Functions

You will note in the code below I am using static functions to easily start the new thread, and I could also use a static Shutdown() function from the GameThread if I ever needed to shut the thread down in a hurry (such as player exiting the game)

Performance

I first computed the first 50,000 prime numbers using the Task Graph System, and creating 50,000 tasks (1 for each prime to find).

In the code you see in this tutorial, I instead created a dedicated thread to calculate the first 50,000 prime numbers!

The performance benefit was phenomenal!

My fps stayed solid 90 for the entiring running of this thread in code below.

Whereas for with the task graph system, as I got closer to 50,000 the fps dropped by a max of 40.

For larger tasks make sure to try out actual multi-threading!

Video

The below is video for the multi-task version, which had marked fps drop as compared with this method of creating an actual thread.

It's the same general idea though, the first 50,000 prime numbers get computed while you continue to do whatever you want in main game thread :)

width="560" height="315" src="https://www.youtube.com/embed/cgELOodtoSU" frameborder="0" allowfullscreen="">

.H

//~~~~~ Multi Threading ~~~
class 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<uint32>* PrimeNumbers;
 
	/** The PC */
	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;
 
	//Done?
	bool IsFinished() const
	{
		return PrimesFoundCount >= TotalPrimesToFind;
	}
 
	//~~~ Thread Core Functions ~~~
 
	//Constructor / Destructor
	FPrimeNumberWorker(TArray<uint32>& TheArray, const int32 IN_PrimesToFindPerTick, AVictoryGamePlayerController* IN_PC);
	virtual ~FPrimeNumberWorker();
 
	// Begin FRunnable interface.
	virtual bool Init();
	virtual uint32 Run();
	virtual void Stop();
	// End FRunnable interface
 
	/** Makes sure this thread has stopped properly */
	void EnsureCompletion();
 
 
 
	//~~~ Starting and Stopping Thread ~~~
 
 
 
	/* 
		Start the thread and the worker from static (easy access)! 
		This code ensures only 1 Prime Number thread will be able to run at a time. 
		This function returns a handle to the newly started instance.
	*/
	static FPrimeNumberWorker* JoyInit(TArray<uint32>& TheArray, const int32 IN_TotalPrimesToFind, AVictoryGamePlayerController* IN_PC);
 
	/** Shuts down the thread. Static so it can easily be called from outside the thread context */
	static void Shutdown();
 
        static bool IsThreadFinished();
 
};

.CPP

//***********************************************************
//Thread Worker Starts as NULL, prior to being instanced
//		This line is essential! Compiler error without it
FPrimeNumberWorker* FPrimeNumberWorker::Runnable = NULL;
//***********************************************************
 
FPrimeNumberWorker::FPrimeNumberWorker(TArray<uint32>& 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;
 
	const bool bAutoDeleteSelf = false;
	const bool bAutoDeleteRunnable = false;
	Thread = FRunnableThread::Create(this, TEXT("FPrimeNumberWorker"), bAutoDeleteSelf, bAutoDeleteRunnable, 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);
 
	//While not told to stop this thread 
	//		and not yet finished finding Prime Numbers
	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<uint32>& 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;
}

Starting the thread

//In the .h for the player controller
// this is the actual data
TArray<uint32> PrimeNumbers;


//player controller .cpp
//Multi-threading, returns handle that could be cached.
//		use static function FPrimeNumberWorker::Shutdown() if necessary
FPrimeNumberWorker::JoyInit(PrimeNumbers, 50000, this);

Thread Management

You should look in the code base for "FRunnable" to see expanded uses of multi threading and lock / unlocking protection.

I used a simple example to get you started, but there's a lot to consider when multi-threading :)

Using Sleep for Thread Management

You should consider using

FPlatformProcess::Sleep(seconds);

to prevent 1 thread from taking too many system resources :)

What Not to Do

  • Do not try to modify, create, or delete UObjects from other threads!

You can prepare all the data / do all the calculations, but only the game thread should be actually spawning / modifying / deleting UObjects / AActors.

  • Dont try to use TimerManager outside of the game thread :)
  • Don't try to draw debug lines/points etc, as it will likely crash, ie DrawDebugLine(etc...)

Timer Functions in GameThread

You can run a timer function in the game thread to periodically check on the data being gathered by the other threads you create.

Conclusion

Enjoy!

【嘉立创EDA】PCB金属包边设计快捷方法 本文使用嘉立创EDA,描述如何在PCB设计时,快速增加边框包边设计,特别是金属包边(伪)——这里标记(伪)是因为该这里的包边特指不含边缘壁。请参考本文时特别注意!本文将此过程记录,以供有需要的读者参考。 阅读详情

相关推荐

STM32H723ZGT6-单ADC极限采样率实战与分辨率权衡

本文通过实战测试,深入探讨了STM32H723ZGT6微控制器中单ADC模块的极限性能。文章详细展示了如何通过CubeMX配置时钟树、ADC参数、定时器触发与DMA,实测得出在16位分辨率下最高稳定采样率约为4.6MHz,而将分辨率降至8位后,采样率可提升至约6.2MHz,并分析了速度与分辨率之间的关键权衡,为高速数据采集项目提供选型与优化参考。

weixin_29240711的博客 301

【UE4 C++ 基础知识】<12> 多线程——FRunnable

【UE4 C++ 基础知识】 多线程——FRunnable

ttod的博客 1368

VIVADO中的IP核在MATLAB中仿真

VIVADO中的IP核在MATLAB中仿真项目简述VIVADO建立FFT IP核MATLAB调用FFT IP核 项目简述 我们都会用MATLAB进行算法验证,但是经常会发现如果VIVADO中调用了IP核,那么最终会发现VIVADO与MATLAB之间的数据不可以统一的对应起来。那么,MATLAB验证的效果就会大大下降,那么可不可以想办法将VIVADO中的IP核封装成一个函数在MATLAB中调用呢?答案是可以的。这篇博客主要以FFT的IP核为例讲解封装成一个函数并且成功在MATLAB中调用。 本次实验所使用的软

zhangningning1996的博客 7000

UE4 C++ 多线程之一 FRunnableThread 以及std::thread

当它走完了Init过后,底层会自动去调用,Run方法,对数据进行一些处理。

qqQQqsadfj的博客 1102

电力远动入门:手把手解析IEC 60870-5-101规约的帧结构与报文交互(基于DL/T634.5101-2002)

本文深入解析IEC 60870-5-101规约的帧结构与报文交互,适用于电力远动通信系统。通过详细讲解规约的基础架构、控制域位定义及典型报文交互流程,帮助工程师快速掌握101规约的核心技术,提升电力自动化系统的调试与维护能力。

weixin_27076351的博客 256

ml307 二次开发

中移物联网旗下4g模组官方网站官方教程id=514官方客户不知道啥时候上班 早上10点也说不在服务时间内 找不到官方的sdk下载路径。

myWorld001的博客 2953

UE4 多线程理解

目前对于UE4来说,要实现多线程有多种方式,主要分为一下几种: FRunnable&amp;&amp;FRunnableThread TaskGraph系统 AsyncTask系统 一、FRunnable&amp;&amp;FRunnableThread UE4遵循C++11,因此,我们可以使用std::thread实现多线程。然而,UE4为了能够实现简单跨平台,实现了自己的多线程机制,也即是...

lz_oases的博客 4136

AD从原理图到PCB超详细教程

我在学习AD的时候,看了网上很多教程,但是东西很杂,有很多条理不清而且废话很多,所以相信大家学习的时候也是遇到一样的困难。我就特地写一篇帖子,整理了一下AD从画原理图开始一直到画完PCB文件的所有步骤,一方面是供大家参考学习,另一方面可以方便我自己学习记忆更加深刻。我用的版本是AD16中文版,大家用新的版本AD20或者AD22应该操作都是差不多的。

人生寂寞如雪 18万+

【UE5 C++课程系列笔记】22——多线程基础——FRunnable和FRunnableThread

介绍FRunnable、FRunnableThread相关概念,并通过结合前面学到的子系统、共享指针和本章内容,介绍一个简单应用案例,实现在线程中循环输出打印信息的功能。

ChaoChao66666的博客 2459

东方财富网 数据访问接口及字段说明

东方财富网 数据访问接口和字段说明

雨中山草 2万+

回归预测 | MATLAB实现TCN时间卷积神经网络多输入单输出回归预测

回归预测 | MATLAB实现TCN时间卷积神经网络多输入单输出回归预测

机器学习之心的博客,关注并私信文章链接,获取对应文章源码和数据。 2496

ue5 多线程

UE5 中的多线程功能允许开发者在应用程序中使用多个线程来提高性能。这可以帮助减少单个线程执行时间,从而提高应用程序的帧率。 UE5 提供了多种方法来创建和使用多线程,包括: FAsyncTask: 这是一种简单的方法,可以在后台线程中执行异步任务。 FThreadSafeCounter: 这是一种线程安全的计数器,可以在多个线程之间共享。 TQueue: 这是一种线程安全的队列,可以在多个线程...

weixin_42610010的博客 1215

智护健康:基于 ESP32 的可穿戴式心率血氧远程监测手环设计与实现

随着健康管理理念的普及,可穿戴式健康监测设备成为刚需。本文设计了一款基于 ESP32 芯片的可穿戴式心率与血氧远程监测手环,通过集成专业生物传感器采集生理数据,借助 ESP32 的无线通信能力实现数据远程传输,搭配手机 APP 与云平台完成数据存储、分析与预警。文中详细阐述了硬件选型、模块接线、软件设计流程及核心代码实现,该手环具备低功耗、高精度、实时性强等特点,可满足日常健康监测与远程照护需求。

weixin_42300449的博客 1205

[UE4][multi-thread]如何创建和终止线程:FRunnableThread::Create()

关键字:UE4 多线程 原文:https://wiki.unrealengine.com/Multi-Threading:_How_to_Create_Threads_in_UE4 相关文档 FRunnable https://docs.unrealengine.com/latest/INT/API/Runtime/Core/HAL/FRunnable/index.html FRun...

玄冬Wong 2266

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

ue4集合类型_UE4 垃圾回收

UE4GC简介UE4为我们搭建了一套UObject对象系统,并且加入了垃圾回收机制,使我们用C++进行游戏开发时更加方便,而且游戏本身也可以极大程度的避免了内存泄漏问题。UE4采用了标记-清扫垃圾回收方式,是一种经典的垃圾回收方式。一次垃圾回收分为两个阶段。第一阶段从一个根集合出发,遍历所有可达对象,遍历完成后就能标记出可达对象和不可达对象了,这个阶段会在一帧内完成。第二阶段会渐进式的清理这些不可...

weixin_35418139的博客 1181

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

在UE中建立一个最简单的FRunnable所需的代码

整理出“建立一个最简单的FRunnable所需的代码”。

主要记录了工作之余胡乱学习的知识,大部分是入门级别的内容。 主要是为了自己未来有用到时能快速上手,相当于是个备忘录。 当然,也很开心其他人可以从中找到对自己有用的信息。^_^ 1606

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

UE4 多线程 创建与使用

UE4 多线程使用分为以下几种: 1.创建标准线程 2.使用线程池 3.使用TaskGraph系统 使用线程时需要注意,不要在非GameThread线程内执行下面几个操作: 不要 创建/ 修改/ 删除 任何 派生自UObject的对象。 不要使用定时器 TimerManager 不要使用任何绘制接口,例如 DrawDebugLine 1...

pzh的博客 7933

UE4异步操作总结【转载】

原文地址:https://blog.ch-wind.com/ue4-async-note/ 虚幻本身有提供一些对异步操作的封装,这里是对这段时间接触到的“非同步”的操作进行的总结。 当前使用的UE4版本为4.18.2。 在虚幻的游戏制作中,如果不是特殊情况一般不会有用到线程的时候。但是由于实际上虚幻内部是有着许多线程机制的。 例如通常的游戏引擎中游戏线程和渲染线程都是独立的,相互之间会存在...

cartzhang的专栏 7915

UE4 FRunnable和FRunnableThread方式,安全的结束线程

关于FRunnable 开启线程,网络上有很多文章,但是对如何安全的结束文章却没有详细的特殊说明,我再使用线程时,又是会出现意外的奔溃。所以在这里特意记录一下 Runnable使用,首先继承FRunnable,实现 Init,Run,Exit,Stop 方法 使用端 通过 FRunnableThread::Create 函数 创建 安全的删除线程 //方式一 if (mRunnable&&mRunnableThread) //mRunnable 实例,mRunnableThr..

weixin_38527697的博客 2545

UE4多线程

PrimeNumberWorker.h class UMyGameInstance; //~~~~~ Multi Threading ~~~ class FPrimeNumberWorker : public FRunnable { static FPrimeNumberWorker* Runnable; FRunnableThread* Thread; TArray<u...

萌蛋蛋の博客 2657

虚幻4 渲染前剔除

实时剔除执行在render函数中的InitViews void FDeferredShadingSceneRenderer::Render(FRHICommandListImmediate& RHICmdList) { bool bDoInitViewAftersPrepass = InitViews(RHICmdList, ILCTaskData, SortEvents); ........

虚幻4引擎工作室 2237

UE4_多线程、异步执行任务

为什么要使用多线程,如果你是想找UE4的多线程资料,肯定不是一个小白了,所以多线程的好处就不用我告诉你了。 如果你想去感受一些多线程的好处,或者想去学习一个多线程的案例。建议,去看看这个博主的文章。 Unreal Engine 4 —— 多线程任务构建 多线程 多线程任务系统详解 该系统核心的几个概念 FQueuedThreadPool: 虚基类,定义线程池常用的接口。FQueueThreadPoolBase 继承FQueuedThreadPool,实现具体的方法。FQueueThreadPoolBa

longyanbuhui的博客 7275

ue4的多线程如何实现

ue4的多线程如何实现讲道理实例创建c++工程新建一个FunctionLibrary在functionlibrary里编写三个函数,并且在cpp里面加以实现再创建一个空类对该项目在vs 上进行生成创建测试用例结论 讲道理 一般要使用多线程技术的,就是该功能点费时,并且降低效率,阻碍体验。 就ue4来说,多线程一般用于后台的计算,信号的发送,检测等。 比如,通过开启一个线程进行心跳检测,确认码的发送...

tianxiaojie_blog的博客 1万+

线程之线程概念

典型的UNIX进程可以看成只有一个控制线程:一个进程在同一时刻只做一件事情。有了多个控制线程(或简称为线程)以后,在程序设计时可以把进程设计成在同一时刻能够做不止一件事,每个线程处理各自独立的任务。这种方法有很多好处: 通过为每种事件类型的处理分配单独的线程,能够简化处理异步事件的代码。每个线程在进行事件处理时可以采用同步编程模式,同步编程模式要比异步编程模式简单得多。 多个进程必须...

weixin_30576859的博客 216

【UE4基础】UE4 垃圾回收

UE4GC简介 UE4为我们搭建了一套UObject对象系统,并且加入了垃圾回收机制,使我们用C++进行游戏开发时更加方便,而且游戏本身也可以极大程度的避免了内存泄漏问题。 UE4采用了标记-清扫垃圾回收方式,是一种经典的垃圾回收方式。一次垃圾回收分为两个阶段。第一阶段从一个根集合出发,遍历所有可达对象,遍历完成后就能标记出可达对象和不可达对象了,这个阶段会在一帧内完成。第二阶段会渐进式的清理这些不可达对象,因为不可达的对象将永远不能被访问到,所以可以分帧清理它们,避免一下子清理很多UObject,比如

yekong1225的专栏 5432

UE4 线程(FRunnable)

class MyThread : public FRunnable { private: MyThread(uint8 *pixcel); ~MyThread(); virtual uint32 Run() override; virtual void Stop() override; private: FRunnableThread *runnableThread = nullptr...

学习是为了探索这个世界的本质 4464
上一篇: 开源C/C++网络库比较:ACE、livevent和Boost
下一篇: 从UE3到UE4
凭谁问
博客等级 码龄15年 178粉丝 16原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址