开发者

Inter-process lock

开发者 https://www.devze.com 2023-01-16 09:36 出处:网络
I am writing a system for automatically recalculating the results of costly methods, and then storing them in a cache. The cache may be distributed, meaning (obviously) multiple processes can access i

I am writing a system for automatically recalculating the results of costly methods, and then storing them in a cache. The cache may be distributed, meaning (obviously) multiple processes can access i开发者_JAVA百科t.

On the first invocation of the method to cache the result for, I want to spawn a thread that will periodically recalculate the result of the method and update the cache.

I want only a single thread of execution to be spawned per cache item. In a multi-process environment, can this be achieved using a cross process mutex such as this?

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

Are there any pitfalls with this approach?

Edit:

Truth table for my implementation:

// 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


In short, I believe that this is a good approach. The only pitfall is mutex identification - if at all possible, tell secondary threads about the mutex by its handle. If named mutexes must be used, you might want to name the mutex the same as your process UUID to promote uniqueness.


On second thought, there may be an easier way to do this. Given your description of the cache being "periodically recalculated", instead of having threads, you could just have a central System.Threading.Timer. Since it can only be associated with a single callback, there is no risk of multiple threads attempting to rewrite the cache. The only caveat is that this timer event would need to do a single write to the cache memory in an atomic fashion (without being interrupted by another thread in mid-write).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号