Whats a good way to read/write lock

I have a large TMap of data which I read from alot, but also sometimes write to. I have been using FSopeLock every time in read or write the TMap, to make it threadsafe. However FScopeLock is somewhat inefficient because it does not allow two threads to read the Tmap at the same time.

Could anyone recommend a threadsafe read/write technique?

There is FRWScopeLock which is a read/write lock. When constructed with an FRWLock critical section, you also specify whether it’s a read or a write. Multiple reads are allowed, only one write is allowed and reading & writing simultaneously is prevented.

I tried this but didnt manage to use it.
It caused a freeze/deadlock for me.

I think the reason for that, Is because I tried to write lock the FRWLock within the same scope that I readLocked it. Is there a way to avoid that?

Yeah, that sounds like it would absolutely cause a deadlock.

I think the only general answer to that is “don’t nest them”. Beyond that I’d have to see code, or you could use the critical section without the scope lock and call the member functions on the FRWLock directly. Then within one scope you could do:

RWCS.ReadLock( )
// do read only stuff here
RWCS.ReadUnlock( )

RWCS.WriteLock( )
// do write stuff here
RWCS.WriteUnlock( )

or you could assume worst case for the scope and use the write lock for the whole scope because it could write and only use the read locks for the places where you actually only read.

1 Like