- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
这是任务:我需要根据文件名进行锁定。最多可以有一百万个不同的文件名。 (这用于大规模的基于磁盘的缓存)。我想要低内存使用率和低查找时间,这意味着我需要一个 GC 锁定字典。 (字典中只能存在正在使用的锁)。
回调操作可能需要几分钟才能完成,因此全局锁定是 Not Acceptable 。高吞吐量至关重要。
我已经在下面发布了我当前的解决方案,但我对它的复杂性不满意。
编辑:请不要发布不是 100% 正确的解决方案。例如,允许从“获取锁定对象”阶段和“锁定”阶段之间的字典中删除锁的解决方案是不正确的,无论它是否是“可接受的”设计模式。
还有比这更优雅的解决方案吗?
谢谢!
[编辑:我根据 RobV 的建议更新了我的代码以使用循环与递归]
[编辑:再次更新代码以允许“超时”和更简单的调用模式。这可能是我使用的最终代码。仍然与原始帖子中的基本算法相同。]
[编辑:再次更新代码以处理回调中的异常而不孤立锁对象]
public delegate void LockCallback();
/// <summary>
/// Provides locking based on a string key.
/// Locks are local to the LockProvider instance.
/// The class handles disposing of unused locks. Generally used for
/// coordinating writes to files (of which there can be millions).
/// Only keeps key/lock pairs in memory which are in use.
/// Thread-safe.
/// </summary>
public class LockProvider {
/// <summary>
/// The only objects in this collection should be for open files.
/// </summary>
protected Dictionary<String, Object> locks =
new Dictionary<string, object>(StringComparer.Ordinal);
/// <summary>
/// Synchronization object for modifications to the 'locks' dictionary
/// </summary>
protected object createLock = new object();
/// <summary>
/// Attempts to execute the 'success' callback inside a lock based on 'key'. If successful, returns true.
/// If the lock cannot be acquired within 'timoutMs', returns false
/// In a worst-case scenario, it could take up to twice as long as 'timeoutMs' to return false.
/// </summary>
/// <param name="key"></param>
/// <param name="success"></param>
/// <param name="failure"></param>
/// <param name="timeoutMs"></param>
public bool TryExecute(string key, int timeoutMs, LockCallback success){
//Record when we started. We don't want an infinite loop.
DateTime startedAt = DateTime.UtcNow;
// Tracks whether the lock acquired is still correct
bool validLock = true;
// The lock corresponding to 'key'
object itemLock = null;
try {
//We have to loop until we get a valid lock and it stays valid until we lock it.
do {
// 1) Creation/aquire phase
lock (createLock) {
// We have to lock on dictionary writes, since otherwise
// two locks for the same file could be created and assigned
// at the same time. (i.e, between TryGetValue and the assignment)
if (!locks.TryGetValue(key, out itemLock))
locks[key] = itemLock = new Object(); //make a new lock!
}
// Loophole (part 1):
// Right here - this is where another thread (executing part 2) could remove 'itemLock'
// from the dictionary, and potentially, yet another thread could
// insert a new value for 'itemLock' into the dictionary... etc, etc..
// 2) Execute phase
if (System.Threading.Monitor.TryEnter(itemLock, timeoutMs)) {
try {
// May take minutes to acquire this lock.
// Trying to detect an occurence of loophole above
// Check that itemLock still exists and matches the dictionary
lock (createLock) {
object newLock = null;
validLock = locks.TryGetValue(key, out newLock);
validLock = validLock && newLock == itemLock;
}
// Only run the callback if the lock is valid
if (validLock) {
success(); // Extremely long-running callback, perhaps throwing exceptions
return true;
}
} finally {
System.Threading.Monitor.Exit(itemLock);//release lock
}
} else {
validLock = false; //So the finally clause doesn't try to clean up the lock, someone else will do that.
return false; //Someone else had the lock, they can clean it up.
}
//Are we out of time, still having an invalid lock?
if (!validLock && Math.Abs(DateTime.UtcNow.Subtract(startedAt).TotalMilliseconds) > timeoutMs) {
//We failed to get a valid lock in time.
return false;
}
// If we had an invalid lock, we have to try everything over again.
} while (!validLock);
} finally {
if (validLock) {
// Loophole (part 2). When loophole part 1 and 2 cross paths,
// An lock object may be removed before being used, and be orphaned
// 3) Cleanup phase - Attempt cleanup of lock objects so we don't
// have a *very* large and slow dictionary.
lock (createLock) {
// TryEnter() fails instead of waiting.
// A normal lock would cause a deadlock with phase 2.
// Specifying a timeout would add great and pointless overhead.
// Whoever has the lock will clean it up also.
if (System.Threading.Monitor.TryEnter(itemLock)) {
try {
// It succeeds, so no-one else is working on it
// (but may be preparing to, see loophole)
// Only remove the lock object if it
// still exists in the dictionary as-is
object existingLock = null;
if (locks.TryGetValue(key, out existingLock)
&& existingLock == itemLock)
locks.Remove(key);
} finally {
// Remove the lock
System.Threading.Monitor.Exit(itemLock);
}
}
}
}
}
// Ideally the only objects in 'locks' will be open operations now.
return true;
}
}
使用示例
LockProvider p = new LockProvider();
bool success = p.TryExecute("filename",1000,delegate(){
//This code executes within the lock
});
最佳答案
根据您对文件的处理方式(您说的是基于磁盘的缓存,所以我假设读取和写入)然后我建议尝试基于 ReaderWriterLock 的操作, 如果你可以升级到 .Net 3.5 然后尝试 ReaderWriterLockSlim相反,因为它表现得更好。
作为减少示例中潜在无限递归情况的一般步骤,将代码的第一位更改为以下内容:
do
{
// 1) Creation/aquire phase
lock (createLock){
// We have to lock on dictionary writes, since otherwise
// two locks for the same file could be created and assigned
// at the same time. (i.e, between TryGetValue and the assignment)
if (!locks.TryGetValue(key, out itemLock))
locks[key] = itemLock = new Object(); //make a new lock!
}
// Loophole (part 1):
// Right here - this is where another thread could remove 'itemLock'
// from the dictionary, and potentially, yet another thread could
// insert a new value for 'itemLock' into the dictionary... etc, etc..
// 2) Execute phase
lock(itemLock){
// May take minutes to acquire this lock.
// Real version would specify a timeout and a failure callback.
// Trying to detect an occurence of loophole above
// Check that itemLock still exists and matches the dictionary
lock(createLock){
object newLock = null;
validLock = locks.TryGetValue(key, out newLock);
validLock = validLock && newLock == itemLock;
}
// Only run the callback if the lock is valid
if (validLock) callback(); // Extremely long-running callback.
}
// If we had an invalid lock, we have to try everything over again.
} while (!validLock);
这用一个循环代替了你的递归,它避免了无限递归引起 StackOverflow 的任何机会。
关于c# - 多线程谜语的更好解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5565395/
据我所知,根本不为元素呈现 HTML,或添加 display:none,似乎具有完全相同的行为:两者都使元素消失并且不与 HTML 交互。 我正在尝试禁用和隐藏一个复选框。所以HTML的总量很小;我无
我刚刚读了Android Architecture Tutorial: Developing an App with a Background Service (using IPC) .基本上是 让服
我有两个查询具有相同的结果,现在我想知道哪个查询更优化? 在选择中: select t1.*, sum(t2.value) as total_votes from table1 t1 left joi
有人告诉我,对于 I/O 绑定(bind)的应用程序,非阻塞 I/O 会更好。对于 CPU 密集型应用程序,阻塞 I/O 会好得多。我找不到这种说法的原因。试过谷歌,但很少有文章只是触及这个话题而没有
我有一个算法可以在数字列表中寻找好的对。一个好的配对被认为是索引 i 小于 j 且 arr[i] 1: # Finding the mid of the array
我有一个算法可以在数字列表中寻找好的对。一个好的配对被认为是索引 i 小于 j 且 arr[i] 1: # Finding the mid of the array
我从 API 收到一个 json,我需要解析并修改一个属性值。问题是,我收到的 json 数据的嵌套结构不一致,我无法控制它。 这将禁止我指定在特定深度(如 parsedJson.children[0
我有 451 个城市的坐标。现在我想计算每个城市之间的距离,然后根据该距离对一些结果进行排序。现在我有两个选择: 我可以运行一个循环来计算每个可能的城市组合的距离并将它们存储到一个表中,这将产生大约
对于返回相同结果的不同查询,我有两个查询计划我想知道是否有人可以告诉我哪个“更好”,以及为什么。 SELECT * FROM bids order by (select ranking from us
关闭。这个问题需要更多focused .它目前不接受答案。 想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post . 关闭 7 年前。 Improve this qu
我有一个二维数组。我需要尽可能快地对其执行一些操作(函数每秒将被调用十几次,所以让它变得高效会很好)。 现在,假设我想获取元素 A[i][j],简单地使用 A[i][j] 在速度上有什么不同吗和 *(
在声明或使用字符串的代码中,我通常会看到开发人员这样声明它: string randomString = @"C:\Random\RandomFolder\ThisFile.xml"; 代替: str
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: Why don't CSS resets use '*' to cover all elements? 我正
如果我有一个包含许多重复项的 python 列表,并且我想遍历每个项目,而不是重复项,最好使用一个集合(如 set(mylist),或者找到另一种方法来创建没有重复的列表?我想只是循环遍历列表并检查重
在阅读常量接口(interface)反模式时,我发现没有实例的最终常量类比常量接口(interface)更好。 请解释一下怎么做? public interface ConstIfc { publ
我正在查看我继承的一些旧代码,我真的不喜欢某些地方的风格。我真的不喜欢它的外观的一件事是: bool func() { bool ret = true; ret &= test1();
关闭。这个问题是opinion-based 。目前不接受答案。 想要改进这个问题吗?更新问题,以便 editing this post 可以用事实和引文来回答它。 . 已关闭 4 年前。 Improv
我经常发现自己试图使用 boost/QT 信号解耦对象。实现这一点的简单方法是针对我要通信的每个具体类型,创建一个新的信号和插槽签名并连接所有相关对象。这导致了访问者模式,理想情况下我想发出一个访问者
我正在 https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html 上阅读有关 lambda 的内容 在方法
public List getInts() { List xs = new ArrayList(); xs.add(1); // return Collections.unmo
我是一名优秀的程序员,十分优秀!