Hi, I’m new to UE5 and trying to make a simplest multithreading function.
void AThreadTester::RunStep3()
{
int32 NumThreads = 20; // Number of threads to create
// Array to hold the promises for each thread
TArray<TPromise<TArray<int>>*> Promises;
Promises.Reserve(NumThreads);
TDiscardableKeyValueCache<int32, int> ThreadResultsCache;
// Create promises and run threads
for (int32 i = 0; i < NumThreads; ++i)
{
// Create a new promise for this thread
TPromise<TArray<int>>* Promise = new TPromise<TArray<int>>();
Promises.Add(Promise);
// Set up the callback for the promise
Promise->GetFuture().Next([i, &ThreadResultsCache](TArray<int> Result)
{
UE_LOG(LogTemp, Warning, TEXT("Thread %d result: %d"), i, Result.Num());
ThreadResultsCache.Add(i, Result.Num());
});
// Create a new instance of MyRunnable2 and add it to the Runnables array
MyRunnable2* Runnable = new MyRunnable2(Promise);
UE_LOG(LogTemp, Warning, TEXT("Thread %d Added"), i);
}
UE_LOG(LogTemp, Warning, TEXT("All started"));
}
This function got some error after adding the line for writing to TDiscardableKeyValueCache, though it is a thread safe struct as I was told. The error message was “Exception thrown at 0x00007FFF3E69BD90 (UnrealEditor-Tester.dll) in UnrealEditor.exe: 0xC0000005: Access violation reading location 0x0000000000000008.” on this line in “Future.h”
auto TFutureBase<InternalResultType>::Next(Func Continuation) //-> TFuture<decltype(Continuation(Get()))> { return this->Then([Continuation = MoveTemp(Continuation)](TFuture<InternalResultType> Self) mutable { return Continuation(Self.Get()); <--- Exception Thrown }); }