ReaderWriterLock数组 [英] ReaderWriterLock for array

查看:145
本文介绍了ReaderWriterLock数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,表示库存,有近50个元素(项目:一些costum对象),我需要一个readerwritelock它(好吧,我想一个简单的锁就足够太)。它应该同时支持参考变化和价值变化。

I have an array, that represents an inventory, with nearly 50 elements (items: some costum objects) and I need a readerwritelock for it (okay, i think a simple lock would be enough too). It should support both reference changing and value changing.

由于读取和写入阵列的不同位置是线程安全的(的证明)我要确保多个读/在同一阵列位置写操作也是线程安全的。

As reading and writing to different position of the array is threadsafe (Proof) I want to ensure that multiple read/write operations on the same array position is also threadsafe.

我一定能创造50 readerwriterlocks,但我不希望出现这种情况;)
是有办法存档吗? (我知道ConcurrentList /词典/等。但我想一个数组...)

I surely could create 50 readerwriterlocks, but I don't want that ;) Is there a way to archive this? (I know ConcurrentList/Dictionary/etc. but I want an array...)

感谢

推荐答案

如果你的替换的数组中的引用,那么这已经是安全的,因为参考互换本质上是原子的。所以,你可以使用:

If you are replacing the references in the array, then this is already safe, since reference swaps are inherently atomic. So you can use:

var val = arr[index];
// now work with val

var newVal = ...
arr[index] = newVal;



完全安全的,至少在避免撕裂引用条款。因此一个务实的选择是为使对象不可变,只是使用上面。如果需要更改值,取一个本地副本,使从基于一个新的版本,然后交换他们。如果丢失更新是一个问题,那么 Interlocked.CompareExchange 并重新申请循环可以非常成功地使用(即你继续你重新申请变更,直到你赢)。这避免了需要的任何的锁定

perfectly safely, at least in terms of avoiding torn references. So one pragmatic option is to make the object immutable, and just employ the above. If you need to change the value, take a local copy, make a new version based from that, and then swap them. If lost updates are a problem, then Interlocked.CompareExchange and a re-apply loop can be used very successfully (i.e. you keep reapplying your change until you "win"). This avoids the need for any locking.

如果,然而,你是突变的个体对象,则该游戏更改。你可以使对象的内部的线程安全的,但这通常是不漂亮。你可以有对所有对象的单个锁。但是,如果你想细粒度锁,那么你将需要多个锁

If, however, you are mutating the individual objects, then the game changes. You could make the object internally thread-safe, but this is usually not pretty. You could have a single lock for all the objects. But if you want granular locking then you will need multiple locks.

我的建议是:使对象不可变和只使用原子基准交换伎俩

My advice: make the object immutable and just use the atomic reference-swap trick.

这篇关于ReaderWriterLock数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆