相关疑难解决方法(0)

线程安全的memoization

让我们以Wes Dyer的函数memoization方法为出发点:

public static Func<A, R> Memoize<A, R>(this Func<A, R> f)
{
  var map = new Dictionary<A, R>();
  return a =>
    {
      R value;
      if (map.TryGetValue(a, out value))
        return value;
      value = f(a);
      map.Add(a, value);
      return value;
    };
}
Run Code Online (Sandbox Code Playgroud)

问题是,当从多个线程使用它时,我们可能会遇到麻烦:

Func<int, int> f = ...
var f1 = f.Memoize();
...
in thread 1:
var y1 = f1(1);
in thread 2:
var y2 = f1(1);
// We may be recalculating f(1) here!
Run Code Online (Sandbox Code Playgroud)

我们试着避免这种情况.锁定map:

public static Func<A, R> …
Run Code Online (Sandbox Code Playgroud)

c# multithreading locking memoization thread-safety

23
推荐指数
2
解决办法
4205
查看次数

标签 统计

c# ×1

locking ×1

memoization ×1

multithreading ×1

thread-safety ×1