We avoid date races on mutable data by keeping it confined to a single thread at a time. By doing this, we prevent other threads from reading or writing the data directly. One way of achieving this is, using “confinement” strategy.

It is a common practise to share a variable/field between goroutines in a pipeline by passing its memory address from one stage to the next over a channel. If each stage of the pipeline refrains from accessing the variable/field after sending it to the next stage, then all accesses to the variable/field are sequential. As a result, the variable/field is confined to one stage of the pipeline then confined to the next and next so on. This is called  serial confinement. Since other goroutines cannot access the variable/field directly, they must use a channel to send the confining goroutine a request to manipulate the variable/field which is what meant by “Do not communicate by sharing memory; instead, share memory by communicating” in Golang.

  • Don’t communicate by sharing memory - Assume that there are multiple threads that want to read/write a shared variable. For example they would use mutexes to lock memory in order to prevent others from reading/writing on it until the operation is done. Here they lock memory one at a time then unlock it as soon as they are done with it so that the next one can pick it up.

#go #golang

Using Serial Confinement Discipline to Achieve Thread Safety in Golang
1.65 GEEK