How to take care of shared resources between C++ and blueprint

I’m writing a C++ code that write a packet data to a structure every time the application receives network packets.
If I want to read the member variables in the structure from a blueprint script, should I take care of read/write racing problem?
Is there any special mechanism that can handle this read/write problem in UE4?

You may need a “synchronization object” in order to handle those race conditions.

When you search for “FScopeLock ScopeLock” project-wide you will get a lot of examples.

“FScopeLock” uses a so called “critical section” which basically waits for other threads when they have locked the section as well before the code continues to execute.

You probably want to lock any accessor-functions on the main-thread while other threads (network) can change the data as well.

Looks like it could be sufficient to wrap getters/setters with one critical section.

But it depends on how often the threads have to wait for each other.

It can be the better approach to copy any critical data on the main-thread and synchronize it at a specific time.

Hi djchase,

Thank you for your kind & helpful advice!

Yes, that’s exactly what I’m looking for. I’ll try to use FScopeLock in accessor-functions so that reader/writer should get the lock before entering their critical section.

BTW, I’m writing the UDP receiver in MyGameInstance.cpp as follows, refering to Rama’s UDP receiver.

    UDPReceiver = new FUdpSocketReceiver(ListenSocket, ThreadWaitTime, TEXT("UDP RECEIVER"));
    UDPReceiver->OnDataReceived().BindUObject(this, &ARamaUDPReceiver::Recv);

ARamaUDPReceiver::Recv plays the role of a shared resource writer in my case. Since it is designated as a call back function, it is executed whenever network packets arrive.
On the other hand, a corresponding shared resource reader is in a Blueprint script (BP_PlayerPawn which inherits Pawn class) and it runs at Tick event timing.
My understanding is that these two code, ARamaUDPReceiver::Recv in MyGameInstance.cpp and Tick event in BP_PlayerPawn, are running on different threads.
That’s why I need to protect the critical section. Is my understanding correct?

Many thanks


Hi Tanaka.

You are welcome :).

Yep, that sounds 100% correct.

The UDPReceiver and the game-ticks run on different threads. Maybe it would be already sufficient to ensure that ARamaUDPReceiver::Recv and BP_PlayerPawn::Tick can never run at the same time.

But it depends when and where the data is accessed. If it can happen, that you access those shared resources outside above two functions, you may want to make the accessor-functions safe as well.

Good luck!

Hi djchase,

Thanks to your explanation, now I gained a deeper understanding on this topic. Thank you!

Best wishes