Synchronizing access to a resource with Mutex
In case the code uses the concurrent access to any resource which is considered to be unsafe for concurrent use, it is necessary to implement a synchronization mechanism to secure the access. Besides the channel usage, Mutex could be leveraged for this purpose. This recipe will show you how.
How to do it...
- Open the console and create the folder
chapter10/recipe01. - Navigate to the directory.
- Create the file
mutex.gowith the following content:
package main
import (
"fmt"
"sync"
)
var names = []string{"Alan", "Joe", "Jack", "Ben",
"Ellen", "Lisa", "Carl", "Steve",
"Anton", "Yo"}
type SyncList struct {
m sync.Mutex
slice []interface{}
}
func NewSyncList(cap int) *SyncList {
return &SyncList{
sync.Mutex{},
make([]interface{}, cap),
}
}
...