什么是线程安全(C#)? (字符串、数组……?)
我对 C# 还很陌生,所以请耐心等待。我对线程安全有点困惑。什么时候某些东西是线程安全的,什么时候不是?
从字段中读取(仅读取之前初始化的内容)是否始终是线程安全的?
//EXAMPLE
RSACryptoServiceProvider rsa = new RSACrytoServiceProvider();
rsa.FromXmlString(xmlString);
//Is this thread safe if xml String is predifined
//and this code can be called from multiple threads?
从数组或列表中访问对象始终是线程安全的(如果您使用 for 循环进行枚举)?
//EXAMPLE (a is local to thread, array and list are global)
int a = 0;
for(int i=0; i<10; i++)
{
a += array[i];
a -= list.ElementAt(i);
}
枚举总是线程安全的吗?
//EXAMPLE
foreach(Object o in list)
{
//do something with o
}
对特定字段写入和读取是否会导致读取损坏(该字段的一半已更改,一半仍保持不变)?
感谢您的所有回答和时间。
编辑:我的意思是如果所有线程都只读取&使用(不是写入或更改)对象。 (除了最后一个问题,很明显我的意思是线程是否同时读取和写入)。因为我不知道普通访问或枚举是否是线程安全的。
I'm quite new to C# so please bear with me. I'm a bit confused with the thread safety. When is something thread safe and when something isn't?
Is reading (just reading from something that was initialized before) from a field always thread safe?
//EXAMPLE
RSACryptoServiceProvider rsa = new RSACrytoServiceProvider();
rsa.FromXmlString(xmlString);
//Is this thread safe if xml String is predifined
//and this code can be called from multiple threads?
Is accessing an object from an array or list always thread safe (in case you use a for loop for enumeration)?
//EXAMPLE (a is local to thread, array and list are global)
int a = 0;
for(int i=0; i<10; i++)
{
a += array[i];
a -= list.ElementAt(i);
}
Is enumeration always/ever thread safe?
//EXAMPLE
foreach(Object o in list)
{
//do something with o
}
Can writing and reading to a particular field ever result in a corrupted read (half of the field is changed and half is still unchanged) ?
Thank you for all your answers and time.
EDIT: I meant if all threads are only reading & using (not writing or changing) object. (except for the last question where it is obvious that I meant if threads both read and write). Because I do not know if plain access or enumeration is thread safe.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不同情况有所不同,但一般来说,如果所有线程都在读取,则读取是安全的。如果有任何正在写入,则读取或写入都不安全,除非可以原子地完成(在同步块内或使用原子类型)。
不确定读取是否可以——你永远不知道幕后发生了什么——例如,getter 可能需要在第一次使用时初始化数据(因此写入本地字段)。
对于字符串,你很幸运——它们是不可变的,所以你所能做的就是读取它们。对于其他类型,您在阅读它们时必须采取预防措施,防止它们在其他线程中发生更改。
It's different for different cases, but in general, reading is safe if all threads are reading. If any are writing, neither reading or writing is safe unless it can be done atomically (inside a synchronized block or with an atomic type).
It isn't definite that reading is ok -- you never know what is happening under the hoods -- for example, a getter might need to initialize data on first usage (therefore writing to local fields).
For Strings, you are in luck -- they are immutable, so all you can do is read them. With other types, you will have to take precautions against them changing in other threads while you are reading them.
在3.10节中,当读写在单个线程上时,C#语言保证读写顺序一致:
多线程、多处理器系统中的事件不一定具有明确定义的相互一致的时间顺序。C# 语言不保证存在一致的顺序。只要不涉及关键执行点,一个线程观察到的一系列写入可能会与另一个线程观察到的顺序完全不同。
因此,该问题无法回答,因为它包含未定义的单词。对于多线程、多处理器系统中的事件,您能否给出“之前”对您意味着什么的精确定义?
该语言保证副作用仅针对关键执行点进行排序,即使如此,在涉及异常时也不会做出任何强有力的保证。再次引用第 3.10 节:
“线程安全”是指两个线程在从列表中读取时始终会观察到一致的结果吗?如上所述,C# 语言对读取变量时观察结果的保证非常有限。对于非易失性读取,您能否给出“线程安全”对您意味着什么的精确定义?
即使在单线程场景中,在枚举集合时修改集合也是非法的。在多线程场景下这样做肯定是不安全的。
是的。我建议您参考第 5.5 节,其中规定:
The C# language guarantees that reads and writes are consistently ordered when the reads and writes are on a single thread in section 3.10:
Events in a multithreaded, multiprocessor system do not necessarily have a well-defined consistent ordering in time with respect to each other. The C# language does not guarantee there to be a consistent ordering. A sequence of writes observed by one thread may be observed to be in a completely different order when observed from another thread, so long as no critical execution point is involved.
The question is therefore unanswerable because it contains an undefined word. Can you give a precise definition of what "before" means to you with respect to events in a multithreaded, multiprocessor system?
The language guarantees that side effects are ordered only with respect to critical execution points, and even then, does not make any strong guarantees when exceptions are involved. Again, to quote from section 3.10:
By "thread safe" do you mean that two threads will always observe consistent results when reading from a list? As noted above, the C# language makes very limited guarantees about observation of results when reading from variables. Can you give a precise definition of what "thread safe" means to you with respect to non-volatile reading?
Even in single threaded scenarios it is illegal to modify a collection while enumerating it. It is certainly unsafe to do so in multithreaded scenarios.
Yes. I refer you to section 5.5, which states:
好吧,我通常认为一切都是线程不安全的。为了在线程环境中快速而脏地访问全局对象,我使用lock(object)关键字。 .Net 有一套广泛的同步方法,例如不同的信号量等。
Well, I generally assume everything is thread unsafe. For quick and dirty access to global objects in an threaded environment I use the lock(object) keyword. .Net have an extensive set of synchronization methods like different semaphores and such.
如果有任何线程正在写入,则读取可能是线程不安全的(例如,如果它们在读取过程中写入,则会遇到异常)。
如果您必须这样做,那么您可以这样做:
这将强制 i 上的线程安全(只要其他线程在使用 i 之前类似地尝试锁定它。一次只有一件事可以锁定引用类型。
就以下而言)枚举,我会参考MSDN:
Reading can be thread-unsafe if there are any threads that are writing (if they write in the middle of a read, for example, they'll be hit with an exception).
If you must do this, then you can do:
This will force thread-safety on i (as long as other threads similarly attempt to lock i before they use it. only one thing can lock a reference type at a time.
In terms of enumeration, I'll refer to the MSDN:
无线程安全的示例:当多个线程递增一个整数时。您可以按照预定的增量数进行设置。但您可能会观察到,int 的增量并没有您想象的那么多。所发生的情况是两个线程可能会增加相同的整数值。这只是您在使用多个线程时可能观察到的过多效果的一个示例。
PS
线程安全增量可通过
Interlocked.Increment(ref i)
获得An example of no thread-safety: When several threads increment an integer. You can set it up in a way that you have a predeterminded number of increments. What youmay observe though, is, that the int has not been incremented as much as you thought it would. What happens is that two threads may increment the same value of the integer.This is but an example of aplethora of effects you may observe when working with several threads.
PS
A thread-safe increment is available through
Interlocked.Increment(ref i)