Sane C++ Libraries
C++ Platform Abstraction Libraries
Loading...
Searching...
No Matches
SC::RWLock Struct Reference

A Read-Write lock that allows multiple concurrent readers but only one writer. More...

#include <Threading.h>

Public Member Functions

 RWLock (const RWLock &)=delete
 
 RWLock (RWLock &&)=delete
 
RWLockoperator= (const RWLock &)=delete
 
RWLockoperator= (RWLock &&)=delete
 
void lockRead ()
 Acquire a read lock. Multiple readers can hold the lock concurrently.
 
void unlockRead ()
 Release a previously acquired read lock.
 
void lockWrite ()
 Acquire a write lock. Only one writer can hold the lock, and no readers can hold it simultaneously.
 
void unlockWrite ()
 Release a previously acquired write lock.
 

Detailed Description

A Read-Write lock that allows multiple concurrent readers but only one writer.

Example:

constexpr int numReaders = 3;
constexpr int numIterations = 100;
RWLock rwlock;
int sharedData = 0;
// Start multiple reader threads
Thread readers[numReaders];
for (int i = 0; i < numReaders; i++)
{
auto readerFunc = [&](Thread& thread)
{
thread.setThreadName(SC_NATIVE_STR("Reader"));
for (int j = 0; j < numIterations; j++)
{
rwlock.lockRead();
volatile int value = sharedData; // Prevent optimization
(void)value;
rwlock.unlockRead();
Thread::Sleep(1); // Small delay to increase contention
}
};
SC_TEST_EXPECT(readers[i].start(readerFunc));
}
// Start a writer thread
Thread writer;
auto writerFunc = [&](Thread& thread)
{
thread.setThreadName(SC_NATIVE_STR("Writer"));
for (int i = 0; i < numIterations; i++)
{
rwlock.lockWrite();
sharedData++;
rwlock.unlockWrite();
Thread::Sleep(1); // Small delay to increase contention
}
};
SC_TEST_EXPECT(writer.start(writerFunc));
// Wait for all threads to finish
for (int i = 0; i < numReaders; i++)
{
SC_TEST_EXPECT(readers[i].join());
}
SC_TEST_EXPECT(writer.join());
SC_TEST_EXPECT(sharedData == numIterations);

Member Function Documentation

◆ lockRead()

void SC::RWLock::lockRead ( )

Acquire a read lock. Multiple readers can hold the lock concurrently.

◆ lockWrite()

void SC::RWLock::lockWrite ( )

Acquire a write lock. Only one writer can hold the lock, and no readers can hold it simultaneously.

◆ unlockRead()

void SC::RWLock::unlockRead ( )

Release a previously acquired read lock.

◆ unlockWrite()

void SC::RWLock::unlockWrite ( )

Release a previously acquired write lock.


The documentation for this struct was generated from the following file: