代码之家  ›  专栏  ›  技术社区  ›  Ben Aston

进程间锁

  •  0
  • Ben Aston  · 技术社区  · 14 年前

    我正在编写一个系统,用于自动重新计算昂贵方法的结果,然后将它们存储在缓存中。缓存可能是分布式的,这意味着(显然)多个进程可以访问它。

    在第一次调用缓存结果的方法时,我希望生成一个线程,该线程将定期重新计算方法的结果并更新缓存。

    我只希望每个缓存项生成一个执行线程。在多进程环境中,是否可以使用这样的跨进程互斥来实现这一点?

    http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx

    编辑:

    我的实现的真值表:

    // in-cache | mutex-found
    //   0            0      //not in cache, no mutex; start thread
    //   1            0      //in cache, no mutex; assume thread already started (re-calculating thread could be in another process)
    //   0            1      //not in cache, mutex found; thread started, do not start thread - log error (and possibly start new thread)
    //   1            1      //in cache, mutex found; thread started, do not start thread
    
    2 回复  |  直到 14 年前
        1
  •  2
  •   Reinderien    14 年前

    总之,我认为这是一个好办法。唯一的陷阱是互斥体标识——如果可能的话,通过它的句柄告诉次线程有关互斥体的信息。如果必须使用命名互斥体,则可能需要将互斥体命名为与进程UUID相同的名称,以提高唯一性。

        2
  •  0
  •   Reinderien    14 年前

    仔细想想,也许有一个更简单的方法。如果您描述的缓存是“定期重新计算的”,而不是线程,那么您可以只使用一个中心缓存系统线程计时器. 由于它只能与单个回调关联,因此没有多个线程试图重写缓存的风险。唯一需要注意的是,此计时器事件需要以原子方式对缓存进行单次写入(在写入过程中不会被另一个线程中断)。