From 1b32e6982a5c1b835966fe32fca480a787d6c217 Mon Sep 17 00:00:00 2001 From: Your Name Date: Mon, 8 Jul 2024 21:07:58 +0800 Subject: [PATCH] sync.mutex start --- .idea/vcs.xml | 1 + sync/mutex.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 sync/mutex.go diff --git a/.idea/vcs.xml b/.idea/vcs.xml index 94a25f7..a9aa77a 100644 --- a/.idea/vcs.xml +++ b/.idea/vcs.xml @@ -2,5 +2,6 @@ + \ No newline at end of file diff --git a/sync/mutex.go b/sync/mutex.go new file mode 100644 index 0000000..a5c2295 --- /dev/null +++ b/sync/mutex.go @@ -0,0 +1,29 @@ +package main + +import ( + "fmt" + "sync" +) + +// 互斥锁 +var x = 0 + +var wg sync.WaitGroup +var lock sync.Mutex + +func add() { + for i := 0; i < 5000; i++ { + lock.Lock() + x = x + 1 + lock.Unlock() + } + wg.Done() +} + +func main() { + wg.Add(2) + go add() + go add() + wg.Wait() + fmt.Println(x) +}