Single-author List <T> thread safety, no counters

Looking through the database code , I looked for an error that was not related to this issue, I noticed that it was List<T>used incorrectly in some places . In particular:

  • There were many threads simultaneously appealing to readers List, but using indexes in Listinstead enumerators.
  • There Listwas one writer.
  • There was synchronization , readers and writers accessed at the same time , but due to the structure of the code, the last element would never be available until the method that executed returned . ListAdd()
  • Items Listhave never been deleted.

In the C # documentation, this should not be thread safe. But it never failed. I am wondering because of the specific implementation List(I assume this is an array, which redistributes when the space ends), is this 1-writer 0-enumerator n-reader add-only script randomly thread safe or is there some kind of unlikely script where it could explode in the current .NET4 implementation ?

edit: An important detail. I have not read some answers. Readers view Listits contents as read-only.

+5
source share
5 answers

. . . , . , .

.Net 4.0, System.Collections.Concurrent, . ConcurrentDictionary, - :

http://msdn.microsoft.com/en-us/library/dd287108.aspx

+2

- , , . , , , , long, . : ! - , , , , .

:. , , , , , , , , . :

for (int index =0 ; index < list.Count; index++)
{
    MyClass myClass = list[index];//ok we are just reading the value from list
    myClass.SomeInteger++;//boom the same variable will be updated from another threads...
}

, , .

, , lock, , .

+1

, 32 , 32 , , , ; . System.Double:

, .

, , 32 . , , . , , .

, List: , , , , .

, , 32 , , , , , , - .

0

, . . - , - , , , . , Add(), . Insert(), .

0

-, , ?

-, , OP.

MrFox , :

  • List ?

, :

  • >

, - , - DWORD - . , , DWORD, 1/2 1/2 .

, , , . List , , .

List , , .

, . , , .

, , , :

  • CopyTo()
  • .

in (, .net) ++:

  List<Object^>^ objects = gcnew List<Object^>^();
  // in some reader thread:
  Monitor::Enter(objects);
  array<Object^>^ objs = gcnew array<Object^>(objects->Count);
  objects->CopyTo(objs);
  Monitor::Exit(objects);
  // use objs array

, .

, : , - - . ZeroMQ. , - .

0

All Articles