Atomic Operations
Let's imagine we want to run independent functions again. However, in this case, we want to modify the value held by a variable. We still want to sum the numbers from 1 to 100, but we want to split the work into two concurrent Goroutines. We can sum the numbers from 1 to 50 in one routine and the numbers from 51 to 100 in another routine. At the end, we will need still to receive the value of 5050, but two different routines can add a number at the same time to the same variable. Let's see an example with only 4 numbers where we want to sum 1, 2, 3, and 4, and the result is 10.
Think of it like having a variable called s:=0
and then making a loop where the value of s
becomes the following:
s=0 s=1 s=3 //(1+2) s=6 s=10
However, we could also have the following loop. In this case, the order in which the numbers are summed is different:
S=0 s=1 s=4 //3+1, the previous value of 1 s=6 //2+4 the previous value of 4 s=10
Essentially, this is just...