【发布时间】:2017-10-25 05:28:05
【问题描述】:
我需要实现三种不同类型的锁定。锁定阅读、写作和排他性。例如,有一个名为 table 的抽象对象,许多事务在不同的线程中工作。
-
读锁是一种允许你同时从不同事务中读取数据的锁,但是如果其中一个事务需要一个表来写,它需要等到所有的读锁都被移除。
写锁允许任何事务从表中读取,但只有一个拥有该表进行写入的事务才能写入表
独占锁是只有一个事务可以访问表时的锁,其他事务在锁被移除时等待。
我正在寻找如何使用 WinApi 和 C/C++ 来实现这一点,我正在尝试这样做
class Table
{
void LockWrite()
{
if (LockLW.IsLock())
LockLW.wait_and_lock();
//
if (LockEx.IsLock())
LockEx.wait();
}
void LockExclusive()
{
{
// it is assumed that this is a thread-safe check
if (readers != 0)
FreeLockRead.wait();
}
//but there is a problem, because in this place some transactions have started to read again
if (LockLW.IsLock())
LockLW.wait_and_lock();
if (LockEx.IsLock())
LockEx.wait_and_lock();
}
void UnLockExclusive()
{
LockEx.unLock();
}
void LockRead()
{
if (LockEx.IsLock())
LockEx.wait();
//Set Lock Read
//a problem, because in this place one of transactions have got LockEx
readers += 1;
}
void UnLockRead()
{
readers -= 1;
if (readers == 0)
FreeLockRead.pulse();
}
mutex LockLW;
mutex LockEx;
event FreeLockRead;
atomic readers;
};
【问题讨论】:
-
this 之类的东西能解决问题吗?
标签: c++ database transactions locking