add PIReadWriteLock, PIReadLocker and PIWriteLocker

This commit is contained in:
2024-11-13 13:56:16 +03:00
parent 4655d72554
commit 0840d807a0
5 changed files with 424 additions and 18 deletions

View File

@@ -39,28 +39,66 @@ public:
class RWL {
public:
void lockWrite() { mutex.lock(); }
void unlockWrite() { mutex.unlock(); }
void lockRead() {}
void unlockRead() {}
void lockWrite() {
PIMutexLocker _ml(mutex);
while (reading > 0 || writing) {
var.wait(mutex);
}
writing = true;
}
void unlockWrite() {
PIMutexLocker _ml(mutex);
writing = false;
var.notifyAll();
}
void lockRead() {
PIMutexLocker _ml(mutex);
while (writing) {
var.wait(mutex);
}
++reading;
}
void unlockRead() {
PIMutexLocker _ml(mutex);
--reading;
var.notifyAll();
}
private:
PIConditionVariable var;
int reading = 0;
bool writing = false;
PIMutex mutex;
};
PIMutex mutex;
PISemaphore sem(10);
PIReadWriteLock rwl;
int main(int argc, char * argv[]) {
/*sem.acquire(2);
piCout << sem.tryAcquire(2);
piCout << sem.available();
return 0;*/
PIThread t_w(
PIThread t_w0(
[] {
// PIMutexLocker _ml(mutex);
piCout << "write start ...";
PIWriteLocker rl(rwl);
piCout << "write0 start ...";
piMSleep(500);
sem.release(11);
piCout << "write end" << sem.available() << "\n";
piCout << "write0 end"
<< "\n";
},
true,
1_Hz);
PIThread t_w1(
[] {
// PIMutexLocker _ml(mutex);
PIWriteLocker rl(rwl);
piCout << "write1 start ...";
piMSleep(500);
piCout << "write1 end"
<< "\n";
},
true,
1_Hz);
@@ -69,33 +107,36 @@ int main(int argc, char * argv[]) {
PIThread t_r0(
[&cnt0] {
// PIMutexLocker _ml(mutex);
PIReadLocker rl(rwl);
piCout << "read0 start ...";
piMSleep(50);
sem.acquire(2);
bool ok = true; // sem.tryAcquire(2, 100_ms);
if (ok) ++cnt0;
piCout << "read0 end" << sem.available() << ok;
// bool ok = rwl.tryLockRead(100_ms);
// if (ok) ++cnt0;
piCout << "read0 end";
// if (ok) rwl.unlockRead();
},
true,
10_Hz);
PIThread t_r1(
[&cnt1] {
// PIMutexLocker _ml(mutex);
// PIReadLocker rl(rwl);
piCout << "read1 start ...";
piMSleep(50);
sem.acquire(2);
bool ok = true; // sem.tryAcquire(2, 100_ms);
bool ok = rwl.tryLockRead(100_ms);
if (ok) ++cnt1;
piCout << "read1 end" << sem.available() << ok;
piCout << "read1 end" << ok;
if (ok) rwl.unlockRead();
},
true,
11_Hz);
piSleep(5.);
piSleep(8.);
t_r0.stopAndWait();
t_r1.stopAndWait();
t_w.stopAndWait();
t_w0.stopAndWait();
t_w1.stopAndWait();
piCout << cnt0 << cnt1;