Thread A goes on to do something else and then runs out of work and needs the results from Thread B.
Thread B is still processing so Thread A calls Sleep to let the OS allow the processor Core that Thread A is on to do something else.
Thread B finishes it’s work and tells the OS to wake up Thread A.
That’s a very HIGH level view. There’s a lot of nuance that goes with this (thread events, load balance across threads vs # of cores on a machine, synchronization privatives / futures, etc). Unless you’re working on slower hardware with limited cores (Nintendo Switch for example) - it’s not something you’ll likely have to deal with.
@ExtraLifeMatt, Thanks! That makes sense. So, if my game is single threaded, then it wouldn’t make much sense to use this. Unless if I’m right in saying that, this is platform independent and works with any threads and not just the threads launched by UE4 (like GameThread, RenderingThread, etc…)?
UE4 by default is multi-threaded. There’s a render thread, worker threads, etc. However, those methods are something you won’t likely need - they’re just there for the level low guys working on the engine and constrained platforms.
In my case, GameThread is launching a worker thread that runs indefinitely(i.e. until we manually send a close/shutdown command). There are few resources shared between this worker thread and GameThread. Code of my worker thread and GameThread related to this FPlatformProcess::Sleep(0) looks like this;
// worker thread, launched by GameThread
void WorkerthreadFunc()
{
while(condition is not met)
{
FPlatformProcess::Sleep(0);
}
// do something with var now that the condition is met
// ...
}
// GameThread
void SomeFunction() // this get's called every Tick()
{
var++; // when var reaches 10, condition on worker thread is met
}
So, in this case, am I right in understanding that worker thread does not block GameThread, but instead waits until the condition is met. So, in a way FPlaformProcess::Sleep(0) is a non-blocking way of synchronization between two threads?
Basically. Depending on the OS, Sleep(0) can become a yield (in which case that thread will go to sleep until the OS decides to re-awaken it - which could be round-robin, or whatever) or it just turns into a Sleep(1) where it sleeps for some minimum amount of time. But yes, the “check some condition and sleep X before checking again” is a pretty common paradigm in multi-threaded programming.