问题描述
是否有跨进程工作的读/写锁定机制(类似于互斥锁,但读/写而不是排他锁定)?我想允许并发读访问,但独占写访问.
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.
推荐答案
没有.正如 Richard 上面提到的,.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.
http://www.joecheng.com/中描述了方法 #1博客/条目/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();
}
另一种选择是:
读取锁定 - 如上所述.写锁定如下(伪代码):
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
必须指出,更有效的方法是可能的,如下所示:http://en.wikipedia.org/wiki/Readers-writers_problem#The_second_readers-writers_problem在上面的文章中查找此解决方案次优"的字样.
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 中的跨进程读写同步原语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!