I need a code example for using unreal's mutex!

Hi, I want just two lines of code example of creating and locking a mutex in UE4 way.

I think FCriticalSection is the mutex type inside of UE4, but I don’t know how to use a function like C++ standard lock_guard. (In standard C++ this function is superior to using lock(), then unlock() if an exception was thrown amid locking, is that the case with unreal as well?)

The code of standard c++ that I’d like to replicate using unreal coding standard is the following:

#include <mutex>
std::mutex GlobalMutex;
foo()
{
std::lock_guard<std::mutex> lock(GlobalMutex);
//...
//rest of code.
//...
}
1 Like

did u find that out ?

FScopeLock

Here is a demo method i did to understand the logic of AsyncTask unsing a FCriticalSection (mutex) to communicate safely with the object calling it:

.h

#include "GenericPlatform/GenericPlatformProcess.h"
#include "Misc/ScopeLock.h" 

...

UFUNCTION(BlueprintCallable)
void PushTask(float duration);

FCriticalSection critical;
bool task_active;

.cpp

void MyClass::PushTask(float duration)
{
	if (critical.TryLock())
	{
		if (task_active)
		{
			UE_LOG(LogTemp, Warning, TEXT("\t\ta task is already running!"));
			critical.Unlock();
		}
		else
		{
			task_active = true;
			// do not forget to unlock here or you might have 
			// a deadlock if the task is super fast
			critical.Unlock();
			UE_LOG(LogTemp, Error, TEXT("task active for %f"), duration);
			AsyncTask(ENamedThreads::AnyThread, [this,duration]() {
				FPlatformProcess::Sleep(duration);
				// 'this' might be destroyed in the meanwhile
				if (this && IsValid(this))
				{
					critical.Lock();
					task_active = false;
					critical.Unlock();
				}
				UE_LOG(LogTemp, Error, TEXT("i slept for %f seconds"), duration);
			});
		}
	}
	else
	{
		UE_LOG(LogTemp, Error, TEXT("Failed to lock critical"));
	}
}

Add this in any actor, and call PushTask from blueprint with a long duration to see the result.