3

For example I have var linkedList = new LinkedList<int>();

Then I add one node. linkedList.AddLast(1);

After that I have two threads respectively calling linkedList.AddLast(2); (same statement).

So can I safely expect it becomes 1->2->2 linked list?

Or it can become 1->2 when race condition happens?

(Maybe it also has visibility issue, but before that I firstly wonder if such race condition can happen.)

cshu
  • 5,654
  • 28
  • 44

4 Answers4

4

This is a question that can easily be answered with a quick little test app. The answer is 1->2 will happen sometimes.

private static void RunTest()
{
    for (int i = 0; i < 100; i++)
    {
        var lst = new LinkedList<int>();

        Parallel.For(1, 51, j =>
        {
            lst.AddLast(j);
        });

        if (lst.Count < 50)
        {
            Console.WriteLine(lst.Count);
        }
    }
}

As has been mentioned, this collection is not thread-safe. You will need to serialize the access or use a built-in thread-safe collection.

Gary.S
  • 7,076
  • 1
  • 26
  • 36
1

So can I safely expect it becomes 1->2->2 linked list?

No, you can't. LinkedList<T> is not thread safe.

From MSDN:

This type is not thread safe. If the LinkedList needs to be accessed by multiple threads, you will need to implement their own synchronization mechanism. A LinkedList can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure.

Stephan Toub in one of his answers says:

A ConcurrentLinkedList was originally introduced in preview and beta releases of .NET 4, but it was subsequently removed prior to .NET 4 RTM because the type imposed a rigid programming model and its performance benefits over just locking on access to a linked list weren't significant enough for the primary scenarios to warrant the type's inclusion.

You may implement your own safe LinkedList<T> with a simple locking mechanism around critical sections.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
0

You can't use LinkedList right-away for multi-threading as it is not a thread safe collection. See how make it thread safe or suggest to choose one of thread safe collections.

Community
  • 1
  • 1
Vladimirs
  • 8,232
  • 4
  • 43
  • 79
0

From MSDN: This type is not thread safe. If the LinkedList needs to be accessed by multiple threads, you will need to implement their own synchronization mechanism.

Andrew Karpov
  • 431
  • 2
  • 7