Question: The C# language specification gives a few guarantees about atomic operations. Assignment of several types, but not ALL types, in C# are guaranteed to be

The C# language specification gives a few guarantees about atomic operations. Assignment of several types, but not ALL types, in C# are guaranteed to be atomic. Section 5.5 of the language specification outlines the types (https://msdn.microsoft.com/en-us/library/aa691278(v=vs.71).aspx) and lists all reference types as having atomic assignment. Consider a Node class for a singly-linked list of integers.

class Node

{ public Node Next; public int Value; public Node(int value, Node next) { Next = next; Value = value; } public Add(int value) { Next = new Node(value, null); } }

Suppose 2 different threads have a reference to the same root node of a singly-linked list, and assume that root is properly allocated with a value within it. What is true about the behavior if both threads call the Add function at the same time? Assume thread A is adding value X and thread B is adding value Y. Assume the root node has a value of 0 and its Next reference set to null before the threads call Add. For this problem assume the "new" operator always succeeds in dynamically allocating content.

The list after both threads complete their addition is guaranteed to have both values X and Y, but there is no guarantee of the order. There is also a guarantee of no runtime exceptions. So the list will either be: root {0} -> node_from_A {X} -> node_from_B {Y}

OR

root {0} -> node_from_B {Y} -> node_from_B {X}

The list after both threads complete their addition is guaranteed to have at LEAST one of the two values X and Y after the root, but there is no guarantee of the order. It also may have both. In addition, there is a guarantee of no runtime exceptions.

The list after both threads complete their addition is guaranteed to have EXACTLY one of the two values X and Y after the root, but there is no guarantee of which one. It will NOT ever have both values. In addition, there is a guarantee of no runtime exceptions.

There is no guarantee of runtime behavior and we may see and exception. Even with the guarantee that the "new Node..." part always succeeds in allocating a new node, we may see a runtime exception.

We won't ever see a runtime exception just from the threads trying to add the values, but memory may be corrupt after both additions complete and the root node may have a bad reference, even with the guarantee of dynamic allocation succeeding. So therefore AFTER the two adds complete if we access the Next field in the root we may get a runtime exception.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!