Hello Devs! I’m trying to work with an array of FVectors across multiple threads. According to my understanding of how arrays work, it should be doable as long as I don’t change it’s size.
So now, is it possible to create an array of FVectors with specified size, so later I can set it’s elements on many threads (of course indexes will be different for each thread)?
In pure C++ I could do something like int* Arr = new int[ElementsCount]; But how to achieve that with TArray<FVector> and won’t it mess up memory management that UE does behind the scenes?
(Of course I could add empty vector in a loop, but that’s not the solution for a few millions elements)
Ahh I didn’t notice such an easy function like Array.SetNum(...), it exactly does the job.
Also I can confirm that the solution worked to scale the array before using ParallelFor, works like a charm for my case.
So in case it’s useful for anyone I leave here reference to what I did:
//Calculate how many traces are needed and set array to have that many elements
int TracesCount = ...;
TArray<FVector> TmpPoints;
TmpPoints.SetNum(TracesCount);
ParallelFor(TracesCount, [&](int32 Idx)
{
//Do trace and some other logic
TmpPoints[Idx] = HitResult.Location;
});
Thanks to that I don’t need to use FCriticalSection, which would slow down this function a lot, because threads would need to wait until they can add variable to the array.
The downside is that now, I have some empty array elements in case the Trace didn’t hit anything, so final array ends up much bigger than it should, but still according to my measurements it’s much faster than locking Mutex.
Does anyone more experienced see any potential errors in this solution?