Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithread adding nodes to LinkedList?

Tags:

c#

.net

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.)

like image 252
cshu Avatar asked May 21 '26 14:05

cshu


1 Answers

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.

like image 115
Gary.S Avatar answered May 23 '26 03:05

Gary.S