.net System.MemberwiseClone and interlocked writes

落爺英雄遲暮 提交于 2019-12-25 08:15:37

问题


When performing a MemberwiseClone of an array of value types:

 var arr = new double[100];

If these doubles are being modified using an Interlocked write on other threads, will the MemberwiseCloned copy be at any risk of having torn doubles in it? I'm not concerned about having slightly stale values, just tearing and the interaction between interlocked and memberwiseclone (which I guess translates to a memory blit type operation?)


回答1:


Yes. On 32bit operating systems this is even guaranteed to have the risk of tearing. On 64bit it is implementation defined. I wouldn't lightly risk it because even if you test that it doesn't happen then your test was only on your particular .NET version and on you particular hardware. You can't really make sure.

On 64bit you can reliably prevent tearing by implementing your own version of clone (which is likely to be not much slower).



来源:https://stackoverflow.com/questions/10998730/net-system-memberwiseclone-and-interlocked-writes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!