Can't use SetActorLocation() in a thread

So I’ve been working on this flocking simulation and it’s working well, but it needs to be optimized. Recently i’ve tried to implement multithreading to it so that the calculations for the next position and setting the boid actor in the next calculated position is done in threads instead of sequentially, hoping that this would improve the performance by a large margin and allow me to spawn more boids for the flock.

There is one problem though, when using SetActorLocation() in the thread, UE4 triggers a breakpoint immidiately on game start on the line where SetActorLocation() was used.

When i noticed that i tried to remove SetActorLocation() from the thread and just put it in the boid actors Tick() function so that the calculations for the next position are done in threads but SetActorLocation() is done sequentially. This resulted in very little improvement of the simulation performance which I’m assuming is because we’re doing the SetActorLocaton() sequentially and there’s too many boids to go through every tick? Or maybe because the SetActorLocation() is expensive to execute?

Here’s the thread class that does the work for each individual boid in the .h file

class CalculateFlockTask : public FNonAbandonableTask
{
public:
	CalculateFlockTask(ABoid* boid);
	~CalculateFlockTask();

	//Requierd by UE4
	FORCEINLINE TStatId GetStatId() const
	{
		RETURN_QUICK_DECLARE_CYCLE_STAT(CalculateFlockTask, STATGROUP_ThreadPoolAsyncTasks);
	}

	
	ABoid* boid;
	TArray<AActor*> DetectOthers(ABoid* boid);
	FVector Align(ABoid* boid, TArray<AActor*> nearbyBoids);
	FVector Cohesion(ABoid* boid, TArray<AActor*> nearbyBoids);
	FVector Separation(ABoid* boid, TArray<AActor*> nearbyBoids);

	void Move(ABoid* boid, float DeltaTime);
	void Flock(ABoid* boid);
	void RotateMesh(ABoid* boid, FVector oldPosition, FVector newPosition);


	void DoWork();
};

This thread class is defined in the same .h file as an actor class called ParallelCalculator. This actor is spawned once upon game start and is given an array of all the boids that are spawned. In it’s Tick() function, it runs a for each loop on the array and creates a thread for each boid in the list to perform the calculations on to update their positions.

This way of creating the thread is inspired by this example where someone creates a thread to calculate prime numbers in the background: Unreal 4 Threading - Running a Task on a Worker Thread - YouTube

Also, here’s the output from “Autos”, apparently the boid that the thread received is set to null, which is weird because when SetActorLocation() is removed from the thread and put into the boids Tick() function, the thread it is able to recognize the boid it received and do calculations for the next position and set it’s variables to different values.