C#多线程:获取读锁有必要吗? [英] C# multi-threading: Acquire read lock necessary?

查看:377
本文介绍了C#多线程:获取读锁有必要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有必要从多个线程读取之前获得一个变量的锁

Is it necessary to acquire a lock on a variable before reading it from multiple threads?

推荐答案

简短的回答是? 。这取决于

The short answer is: it depends.

长的答案是:


  • 如果它是不是共享的价值,也就是说,只有一个线程可以看到它(或使用),你不需要任何同步。

  • If it is not a shared value, i.e, only one thread can see it (or use it), you don't need any synchronization.

如果它是一个一成不变的值,也就是说,您可以设置它只有一次,然后只读过,这是安全无同步这样做(只要第一次写完成之前你不开始阅读)。

If it is an immutable value, i.e., you set it only once and then only ever read, it is safe to do so without synchronization (as long as you don't start reading before the first write completes).

如果这是一个原始类型最多的32位(的如字节 INT ),您可以读取时会过时(旧)的数据。如果不打扰你,你设置。如果陈旧数据是不可取的,使得可变 挥发性 可以解决这个问题,无需额外的同步进行读写。但是,如果你赛车的作家,您将需要遵循相同的意见作为 s以下。

If it is a "primitive" type of at most 32-bits (e.g. byte, short, int) you can get stale (old) data when reading. If that doesn't bother you, you're set. If stale data is undesirable, making the variable volatile can fix this problem without additional synchronization for reads. But if you have racing writers, you will need to follow the same advice as for longs below.

如果这是一个原始类型大于32位长(例如:小数双击),你需要同步,否则,你可以一个值,另一半读半壁江山,并获得疯狂的结果。对于这个建议的方法是使用互锁的 的方法 类,读取和写入。

If it is a "primitive" type longer than 32-bits (e.g. long, decimal, double) you need synchronization, otherwise you could read "half" of one value, "half" of another, and get crazy results. For this the recommended approach is to use the methods in the Interlocked class, for both reads and writes..

如果是引用类型,则需要同步,以避免看到无效状态(杰夫·兰姆的图片例如是一个好的)。该 锁定 声明可能是不够那。同样,你需要锁定的读取和写入操作。

If it is a reference type, you will need synchronization to avoid seeing an invalid state (Jeff Lamb's picture example is a good one). The lock statement might be enough for that. Again, you need to lock for both reads and writes.

有一些其他的考虑要点(多久锁定,例如),但我认为这些都足以回答你的问题。

There are some other points to consider (how long to lock, for example), but I think these are enough to answer your question.

这篇关于C#多线程:获取读锁有必要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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