Thread lock in UE4

Implements a scope lock. This is a utility class that handles scope level locking. It's very useful to keep from causing deadlocks due to exceptions being caught and knowing about the number of locks a given thread has on a resource. Example:

 { 
         /// Synchronize thread access to the following data FScopeLock ScopeLock(SynchObject);
         /// Access data that is shared among multiple threads ... 
         /// When ScopeLock goes out of scope, other threads can access data
 }

Need to include "Runtime/Core/Public/HAL/ThreadingBase.h"

and then difine a param:

FCriticalSection* m_mutex; 

the most convenient way to use critical sections is in conjunction with scope locks, Use it inside the function:

void Func()
{

//none synchronization,unprotected

     {
           //synchronization
           //need to put at first line to indicate this is a scope lock at this {} area
           FScopeLock ScopeLock(m_mutex);
     }

//none synchronization

}

Create instance stream with scope lock example:

FCriticalSection            mutex;

class FStreamingContent : public FRunnable
 {
 public:
     FStreamingContent(FCriticalSection &mutex, std::queue<s_Content> &queue);
     virtual ~FStreamingContent();
     
     FRunnableThread*            thread;
     std::queue<s_Content>        data;
     static FStreamingContent*    inst;
     
     static FStreamingContent*    CreateInstance(const std::string &fileName, FCriticalSection &mutex, std::queue<s_Content> &queue);
        // Implements FRunnable functions
 };

/// call createInstance
{
 std::queue<s_Content> data;
 
 FStreamingContent* streamingContent = FStreamingContent::CreateInstance("myfile.twd", mutex, data);
}

Additional:

https://docs.unrealengine.com/latest/INT/API/Runtime/Core/HAL/FScopeLock/index.html

https://wiki.unrealengine.com/MultiThreading_and_synchronization_Guide

猜你喜欢

转载自avi.iteye.com/blog/2372745