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++
asked Jul 28 '15 at 05:51 PM in C++ Programming
I think You should create a FCriticalSection (or FPThreadsCriticalSection if You want) in the object where the TArray is. For example:
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.
answered Jul 30 '15 at 08:52 AM
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.
answered Jan 12 '18 at 08:30 AM
Follow this question
Once you sign in you will be able to subscribe for any updates here