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 still need 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 four 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...