From 35f86b8c87e7663f5e391e8aed851eab355b634a Mon Sep 17 00:00:00 2001 From: hau Date: Sat, 29 Aug 2020 13:28:01 +0700 Subject: [PATCH] add go mutext --- Development/Go/strings.md | 2 +- Development/Go/sync.md | 43 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 Development/Go/sync.md diff --git a/Development/Go/strings.md b/Development/Go/strings.md index 64a3cf6..57af105 100644 --- a/Development/Go/strings.md +++ b/Development/Go/strings.md @@ -1,6 +1,6 @@ # [strings](https://golang.org/pkg/strings/) -Replace list of strings by using Replacer: +Replace list of strings by using `Replacer`: ```go template := "My city is {city} and my country is {country}" diff --git a/Development/Go/sync.md b/Development/Go/sync.md new file mode 100644 index 0000000..381fc09 --- /dev/null +++ b/Development/Go/sync.md @@ -0,0 +1,43 @@ +# [sync](https://golang.org/pkg/sync/) + +Use `Mutext` to prevent accessing variable from different goroutine at the same time: + +```go +type foo struct { + mu sync.Mutext + + bar map[string]string +} + +func (f *foo) doSomething { + f.mu.Lock() + defer f.mu.Unlock() + + // do the thing +} + +``` + +Use `RWMutex` if there are many readers, and few writers: + +```go +type foo struct { + mu sync.RWMutext + + bar map[string]string +} + +func (f *foo) read { + f.mu.RLock() + defer f.mu.RUnlock() + + // read +} + +func (f *foo) write { + f.mu.Lock() + defer f.mu.Unlock() + + // write +} +```