问题描述
有一个读/写锁定跨流程的工作机制(类似于互斥,但读/写的,而不是排他锁)?我想允许并发读取访问,但独占写访问。
Is there a read/write locking mechanism that works across processes (similar to Mutex, but read/write instead exclusive locking)? I would like to allow concurrent read access, but exclusive write access.
推荐答案
没有。正如理查德上面提到的,有没有这样的在.NET箱子机制。这是如何使用互斥量和信号量来实现它。
No. As Richard noted above, there is no such out of the box mechanism in .NET.This is how to implement it using a mutex and a semaphore.
方法1在 http://www.joecheng.com/描述博客/项/ Writinganinter-processRea.html ,报价:
// create or open global mutex
GlobalMutex mutex = new GlobalMutex("IdOfProtectedResource.Mutex");
// create or open global semaphore
int MoreThanMaxNumberOfReadersEver = 100;
GlobalSemaphore semaphore = new GlobalSemaphore("IdOfProtectedResource.Semaphore", MoreThanMaxNumberOfReadersEver);
public void AcquireReadLock()
{
mutex.Acquire();
semaphore.Acquire();
mutex.Release();
}
public void ReleaseReadLock()
{
semaphore.Release();
}
public void AcquireWriteLock()
{
mutex.Acquire();
for (int i = 0; i < MoreThanMaxNumberOfReadersEver; i++)
semaphore.Acquire(); // drain out all readers-in-progress
mutex.Release();
}
public void ReleaseWriteLock()
{
for (int i = 0; i < MoreThanMaxNumberOfReadersEver; i++)
semaphore.Release();
}
另一种方法是:
An alternative would be:
读锁定 - 同上。写锁定如下(伪code):
Read locking - as above. Write locking as follows (pseudocode):
- Lock mutex
- Busy loop until the samaphore is not taken AT ALL:
-- wait, release.
-- Release returns value;
-- if value N-1 then break loop.
-- yield (give up CPU cycle) by using Sleep(1) or alternative
- Do write
- Release mutex
有必须指出的是更有效的方法是可能的,如这里:寻找在上述文章中的词语这个解决方案是不理想的
It must be noted that more efficient approach is possible, as here: http://en.wikipedia.org/wiki/Readers-writers_problem#The_second_readers-writers_problemLook for the words "This solution is suboptimal" in the article above.
这篇关于在.NET跨进程读写同步灵长类动物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!