Synchronization

Goroutines allow code to be executed concurrently, but the synchronization between values is not ensured out of the box. We can check out what happens when trying to use a variable concurrently with the following example:

func main() {
var i int
go func(i *int) {
for j := 0; j < 20; j++ {
time.Sleep(time.Millisecond)
fmt.Println(*i, j)
}
}(&i)
for i = 0; i < 20; i++ {
time.Sleep(time.Millisecond)
fmt.Println(i)
}
}

We have an integer variable that changes in the main routine—doing a millisecond pause between each operationand after the change, the value is printed.

In another goroutine, there is a similar loop (using another variable) and another print statement that compares the two values. Considering that the pauses are the same, we would expect to see the same values, but this is not the case. We see that sometimes, the two goroutines are out of sync.

The changes are not reflected immediately because the memory is not synchronized instantaneously. We will learn how to ensure data synchronization in the next chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.76.72