How can lock be acquired using FRunnable and FRunnableThread?

Hi I am new to UE4. I want to implement multithreading. I saw that FRunnable and FRunnableThread can be useful. But can didn’t found anything on how we can acquire locks using it. Can someone help me with it?

I suggest you not to use platform dependent solutions and go with UE4 solutions

  1. FScopelock : lock a scope ( a scope is what is written between a two of curly brackets ) so one thread at a time can access it using a pointer to a FCriticalSection. for that to happen it needs a FcriticalSection pointer to be assigned when creating FScopelock. upon creating a Fscopelock it automatically lock the section until Fscopelock get destroyed. it is suggested to have FScopelock as a local variable and not as a pointer so it automatically get destroyed at the end of the scope and therefore releases the lock.
    https://docs.unrealengine.com/latest/INT/API/Runtime/Core/HAL/FScopeLock/index.html

  2. FCriticalSection : a critical section has two main function. Lock and Unlock. the first thread that calls Lock function will be the one that passes through and you have to make sure it will definitely call Unlock function so it let’s the other threads to pass as well.

Note : FCriticalSection has three functions ( Lock, Unlock and TryLock ), but till now TryLock does not work on Mac and just windows. I haven’t tested other platforms but it seems TryLock it’s implemented unified for all platforms

  1. Use of atomic counters (FThreadSafeBool or FThreadSafeCounter ) : these classes provides ways that one thread at a time can increase or decrease or change the value of a function and race won’t happen. FThreadSafeCounter is rather good for situation in which more than one thread needed to be allowed to run a section of a code and not only limited to 1 thread access.
    FThreadSafeCounter : FThreadSafeCounter | Unreal Engine Documentation
    FThreadSafeBool : FThreadSafeBool | Unreal Engine Documentation
1 Like