How to use FPThreadsCriticalSection make data threadsafe

I have been searching the web for examples of how to use FPTreadsCriticalSection, but cannot find anything.
I have one thread that writes to a TArray and another one reading from the same TArray
How can I use FPThreadsCriticalSection to make the TArray threadsafe? Or any other ways of syncronizing? I am not very experienced with threading in c++

Hi.

I think You should create a FCriticalSection (or FPThreadsCriticalSection if You want) in the object where the TArray is. For example:

FCriticalSection MyCritialSection;

Everytime the thread want an access to the TArray (read or write) it should launch the MyCritialSection.Lock() function and when it finish using the TArray launch the MyCritialSection.Unlock() function.

Make sure the Lock() won’t be run twice by the same thread before using Unlock().

Also keep in mind to keep critical section as short as possible to not hunger the second thread.

Bad things are going to happen (locks/crashes) if you somehow fail to unlock the CriticalSection - there could be multiple things that can happen to skip this step, more so if you are using exeption handling.

You can also use FScopeLock in combination of FCriticalSection. Constructor of that thing is going to lock the CriticalSection and the dtor is going to unlock it.

{   
    // scope start
    FScopeLock ScopeLock(&MyCriticalSection);
    ...
    // scope end, critical section will be unlocked here
}