When it comes to threading, I use an update TIck on an Actor to execute deferred delegate callbacks.
https://github.com/tgraupmann/UnrealEngine/blob/4.6-OUYA/Engine/Source/Runtime/Engine/Private/OuyaSDK/OuyaSDK.cpp#L475
void AOuyaSDK::Tick(float deltaSeconds)
{
Super::Tick(deltaSeconds);
if (_mainThreadActions.size() > 0)
{
#if ENABLE_VERBOSE_LOGGING
__android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, "Invoke callback from Tick");
#endif
auto & functionPtr = _mainThreadActions[0];
_mainThreadActions.erase(_mainThreadActions.begin());
functionPtr();
}
}
And then I create actions for other threads that will later execute on the main thread.
void CustomCallbacksInitOuyaPlugin::OnSuccess()
{
#if ENABLE_VERBOSE_LOGGING
__android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, "OnSuccess");
#endif
if (_actor)
{
_actor->_mainThreadActions.emplace_back([]()
{
_actor->OnSuccessInitOuyaPlugin.ExecuteIfBound();
});
}
}
The trouble with this syntax, is that the body of the function blocks can only reference static fields. I haven’t quite figured out how to pass local variables to the anonymous functions.
A cool alternative would be a UMainThreadDelegate that you could invoke from a thread and it would execute on the Actors tick to avoid any thread safe issues similar to what I’ve done.