Sharing Memory Using Goroutines
Let’s learn how to share memory using goroutines.
We'll cover the following
The monitor goroutine
This lesson illustrates how to share data using a dedicated goroutine. Although shared memory is the traditional way that threads communicate with each other, Go comes with built-in synchronization features that allow a single goroutine to own a shared piece of data. This means that other goroutines must send messages to this single goroutine that owns the shared data, which prevents the corruption of the data. Such a goroutine is called a monitor goroutine. In Go terminology, this is sharing by communicating instead of communicating by sharing.
Note: We can use a monitor goroutine instead of traditional shared memory techniques because the implementation with the monitor goroutine is safer, closer to the Go philosophy, and easier to understand.
The logic of the program can be found in the implementation of the monitor()
function. More specifically, the select
statement orchestrates the operation of the entire program. When we have a read request, the read()
function attempts to read from the readValue
channel, which is controlled by the monitor()
function.
This returns the current value of the value
variable. On the other hand, when we want to change the stored value, we call set()
. This writes to the writeValue
channel, which is also handled by the same select
statement. As a result, no one can deal with the shared variable without using the monitor()
function, which is in charge.
Coding example
The code of monitor.go
is as follows:
Get hands-on with 1400+ tech skills courses.