# How can context switch affect the modification of a variable?

float myTotalAmount=0;
void update(float amt){
myTotalAmount+= amt;
}


Task A called update(10);

Calculated myTotalAmount+= amt;

Didn't store the value for myTotalAmount; -------X

Task B called update(5);

Can we say X didn't happen due to context switch? or is Task B able to call update method because context switch happened due to some reason before the X?

Overall I am trying to understand race condition.

A context switch is simply the operating system pausing the execution of one process and starting another. As such, context switches are required for any concurrency problem since, if there are no context switches, there's only one process executing so there is no concurrency.

In your example, the race condition occurs because what the function update really does is:

1. Read the value of myTotalAmount from memory;
2. Add amt to this value;
3. Store the result back in the memory.

Context switches at bad times can cause a race if the processes don't protect against that. Let's say that myTotalAmount currently has value zero.

1. Process B reads the value of myTotalAmount, which is zero.
2. Process B calculates the new value 0+5=5.
3. Context switch.
4. Process A reads the value of myTotalAmount, which is still zero.
5. Process A calculates the new value 0+10=10.
6. Process A writes the value 10 to myTotalAmount.
7. Context switch.
8. Process B writes the value 5 to myTotalAmount.

(Note that ordering the steps 13456728 would give the same result.)

• I took too long to edit. I'd argue that a context switch is not required for a race condition to occur, it is only one path to the problem. The race condition is caused by a multistep process (read - perform addition - write) that allows another thread to perform the same operations. A multi- CPU system can allow multiple threads to run concurrently without context switching, but the result can be the same, process A and B both call update, read the original value, perform calculations and save the result . The value saved depends on which process gets – Brian Hibbert Feb 23 '17 at 14:32
• A multi-CPU system just does several context switches every nanosecond. – gnasher729 Jan 22 at 0:02
• @gnasher729 This is actually not a good model of concurrency in practice. Multi-CPU systems often do load/store reorderings that enable behaviors that wouldn't happen on a single-CPU system. – Gilles Jan 22 at 7:56