MultiThreading in UE4?

I tried using 's Tutorial:

There’s no compile error. But the thread’s Run() function is not executed when I run the game, I don’t know why.
Can you help me ?

GameMode.cpp:

ARoboRev_WinGameMode::ARoboRev_WinGameMode(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
	int i = 0;
	if (GEngine)
		GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Yellow, "Before Thread!");
	ThreadX* t = ThreadX::JoyInit(&i);
	while (i == 0)
	{
		int x = 0;
	}
	if (GEngine)
		GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Yellow, "After Thread!");
}

ThreadX.h:

#include "../Data/PlayerData.h"
class ThreadX : public FRunnable
{
public:
	static ThreadX* Runnable;
	FRunnableThread* Thread;
	int *pData;
	FThreadSafeCounter StopTaskCounter;

	ThreadX(int *p);
	virtual ~ThreadX();
	// Begin FRunnable interface.
	virtual bool Init() override;
	virtual uint32 Run() override;
	virtual void Stop() override;
	// End FRunnable interface

	bool IsFinished() const
	{
		return (StopTaskCounter.GetValue() == 1);
	}

	void EnsureCompletion();

	static ThreadX* JoyInit(int *p);

	static void Shutdown();

	static bool IsThreadFinished();
};

ThreadX.cpp:

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

#include "RoboRev_Win.h"
#include "Engine.h"
#include "../Data/PlayerData.h"
#include "ThreadX.h"

ThreadX* ThreadX::Runnable = NULL;

ThreadX::ThreadX(int *p)
	: StopTaskCounter(0),
	pData(p)
{
	//Link to where data should be stored

	const bool bAutoDeleteSelf = false;
	const bool bAutoDeleteRunnable = false;
	Thread = FRunnableThread::Create(this, TEXT("ThreadX"), bAutoDeleteSelf, bAutoDeleteRunnable, 0, TPri_BelowNormal); //windows default = 8mb for thread, could specify more
}

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

//Init
bool ThreadX::Init()
{
	//Init the Data 
	return true;
}

//Run
uint32 ThreadX::Run()
{
	//Initial wait before starting
	FPlatformProcess::Sleep(0.03);
	*pData = 1;
	return 0;
}

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

ThreadX* ThreadX::JoyInit(int *p)
{
	//Create new instance of thread if it does not exist
	//		and the platform supports multi threading!
	if (!Runnable && FPlatformProcess::SupportsMultithreading())
	{
		Runnable = new ThreadX(p);
	}
	return Runnable;
}

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

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

bool ThreadX::IsThreadFinished()
{
	if (Runnable) return Runnable->IsFinished();
	return true;
}

I would really appreciate if someone answers this.

How Do I PM him? I can’t see the option here really. I have been trying to find that for a long time.

Maybe try PMing :slight_smile:

If you click the name on forums you will have option to PM, but heres link to PM :

https://forums.unrealengine.com/private.php?do=newpm&u=552

Thanks Man… really :smiley: Giving you a thumbs up… :slight_smile:

#Dont Run Threads in Constructors!

oh my!

Please fix this immediately!

Dont try to run threads inside of class constructors!

Also dont run this in game mode, game mode only runs on the server and is a special kind of class.

#Solution

Try the following

 1. use a custom Player Controller Class
 2. Run the thread in BeginPlay() of this player controller class

Let us know how that goes!

I got the thread working. But When I run from visual studio, and hit play in Unreal Editor, the thread executes once.
Next time, if I hit Stop and hit Play again, it doesn’t work…
Not sure why.

But it definitely got me started. Thanks for the help.

Same issue here. Did you ever resolve it?

Not really.
I kinda gave up… I was able to run threads. but wasn;t able to accomplish waht I wanted to… For some reason… :frowning:

Just put Runnable = NULL; as the first thing in the JoyInit function

I ran into similar problem. In the wiki article, talks about his static Shutdown() function, which deletes the thread and turns the pointer into NULL.

If you simply put the Runnable pointer to NULL, you don’t delete the thread and you accumulate running threads until your game grinds to a halt.

Shutdown() must be called outside the thread, say, from the Player Controller class you are going to use.

I’m testing 's Tutorial and ClientMessage() causes crash. I have changed it with UE_LOG

FPrimeNumberWorker::JoyInit(PrimeNumbers, 50000, this); in BeginPlay and FPrimeNumberWorker::Shutdown(); in EndPlay works fine.

This is because the Constructor in Unreal is only called if you Start the editor. If you run it standalone it will always run as expected. Its just the Editor which makes trouble here. Same with static vars. They keep theyr state betwean multiple “Play” runs. The best way (If you have a ssd) is to start Visual Studio and then debug the Game (F5). With this way you also see exactly where NullPtr exceptions happening and you will allways get a fresh Stack of static vars and Constructors. But also dont spawn Threads in the Constructor. Use a initialization funktion (call her initThread or something) which you can call with a beginPlay event.