From a8496afb3502b002fc76336395a87af70b4e742c Mon Sep 17 00:00:00 2001 From: xiaowei <403828237@qq.com> Date: Sun, 13 Feb 2022 14:13:10 +0800 Subject: [PATCH] =?UTF-8?q?add:=20=E9=94=81=E7=9A=84=E4=BD=BF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- channel/mutex/basic/main.go | 34 ++++++++++++++++++++++++++ channel/mutex/rwlock/main.go | 47 ++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 channel/mutex/basic/main.go create mode 100644 channel/mutex/rwlock/main.go diff --git a/channel/mutex/basic/main.go b/channel/mutex/basic/main.go new file mode 100644 index 0000000..e8735b7 --- /dev/null +++ b/channel/mutex/basic/main.go @@ -0,0 +1,34 @@ +package main + +import ( + "fmt" + "sync" + "time" +) + +type Sth struct { + x int64 + wg sync.WaitGroup + lock sync.Mutex +} + +func (s *Sth) add() { + for i := 0; i < 10000; i++ { + s.lock.Lock() + s.x++ + s.lock.Unlock() + } + s.wg.Done() +} + +func main() { + var s Sth + s.wg.Add(2) + go s.add() + go s.add() + s.wg.Wait() + fmt.Println(s) + + time.Sleep(time.Second) + fmt.Println("xiaowei zhaodandan") +} diff --git a/channel/mutex/rwlock/main.go b/channel/mutex/rwlock/main.go new file mode 100644 index 0000000..3668fbf --- /dev/null +++ b/channel/mutex/rwlock/main.go @@ -0,0 +1,47 @@ +package main + +import ( + "fmt" + "sync" + "time" +) + +var ( + x int64 + wg sync.WaitGroup + rwlock sync.RWMutex + lock sync.Mutex +) + +func main() { + start := time.Now() + for i := 0; i < 10; i++ { + wg.Add(1) + go write() + } + for i := 0; i < 100; i++ { + wg.Add(1) + go read() + } + wg.Wait() + fmt.Println("cost:", time.Since(start)) +} + +func read() { + //lock.Lock() + rwlock.RLock() + time.Sleep(time.Millisecond) + //lock.Unlock() + rwlock.RUnlock() + wg.Done() +} + +func write() { + rwlock.Lock() + //lock.Lock() + x = x + 1 + time.Sleep(10 * time.Millisecond) + //lock.Unlock() + rwlock.Unlock() + wg.Done() +}