How would I go about making an FVector thread safe?

could I do this by:

FVector fvec = FVector::ZeroVector;
TSharedPtr<FVector, ESPMode::ThreadSafe> ts_fvec = TSharedPtr<FVector, ESPMode::ThreadSafe>(new FVector(fvec));

Will this be both thread safe to access and read? This documentation has me slightly confused and I’m not sure it’s up to date: Unreal Smart Pointer Library

Specifically,

Reads and copies are always thread-safe.
Writes/resets must be synchronized to be safe.

Does this mean that I have to do my own synchronizing when setting this object or is it just simply stating that that’s what it has to do to set the data? I would look in the code myself to figure this out except that I’m still a bit new to c++ thread safety.

Hi,

I think you are correct in saying that documentation is out of date. For example, TThreadSafeSharedPtr doesn’t exist any more - we use ESPMode::ThreadSafe as a template argument instead.

The basic rule for TSharedPtr is that it is as thread-safe as a raw pointer. That is, you can safely copy/assign/destroy a pointer that you have exclusive access to, even if there are other pointers (which are pointing to the same shared object) being copied/assigned/destroyed on other threads.

But if you ever need to access a pointer which itself (i.e. it doesn’t matter what it’s pointing to) is shared across multiple threads, then you always need explicit synchronisation. You also always need explicit synchronisation for any pointed-to objects.

Basically, it’s only the shared reference count which is thread-safe.

ESPMode::NotThreadSafe is a thing which only really exists for the case where you want sharing for the purpose of ‘garbage collection’ on a single thread, i.e. you want the object to auto-destruct when there are no more references to it. These should never be used for objects intended to be shared across threads.

Hope this helps,

Steve

2 years passed and the documentation is still not updated. Thank you for pointing out to ESPMode::ThreadSafe - that was helpful! ))