List.Add()线程安全 [英] List.Add() thread safety
问题描述
我了解通常情况下,列表不是线程安全的,但是如果线程从不对列表执行任何其他操作(例如遍历列表),则简单地将项目添加到列表中有什么错误吗?
I understand that in general a List is not thread safe, however is there anything wrong with simply adding items into a list if the threads never perform any other operations on the list (such as traversing it)?
示例:
List<object> list = new List<object>();
Parallel.ForEach(transactions, tran =>
{
list.Add(new object());
});
推荐答案
在幕后发生了很多事情,包括重新分配缓冲区和复制元素.该代码将导致危险.很简单,添加到列表时没有原子操作,至少需要更新长度"属性,并且需要将项放在正确的位置,并且(如果有单独的变量)索引也需要要被更新.多个线程可以相互踩踏.如果需要增长,那么还有更多的事情要做.如果某项内容正在写入列表,则其他任何内容都不应读取或写入.
Behind the scenes lots of things happen, including reallocating buffers and copying elements. That code will cause danger. Very simply, there are no atomic operations when adding to a list, at the least the "Length" property needs to be updates, and item needs to be put in at the right location, and (if there's a separate variable) the index needs to be updated. Multiple threads can trample over each other. And if a grow is required then there is lots more going on. If something is writing to a list nothing else should be reading or writing to it.
在.NET 4.0中,我们有并发集合,它们很容易实现线程安全并且不需要锁.
In .NET 4.0 we have concurrent collections, which are handily threadsafe and don't require locks.
这篇关于List.Add()线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!