diff --git a/SUMMARY.md b/SUMMARY.md index 0ea6776..7ca581c 100644 --- a/SUMMARY.md +++ b/SUMMARY.md @@ -60,7 +60,7 @@ * [6.5. 分布式缓存(TODO)](ch6-cloud/ch6-05-cache.md) * [6.6. etcd(TODO)](ch6-cloud/ch6-06-etcd.md) * [6.7. 分布式 id 生成器](ch6-cloud/ch6-07-dist-id.md) - * [6.8. 分布式锁(TODO)](ch6-cloud/ch6-08-lock.md) + * [6.8. 分布式锁(Doing)](ch6-cloud/ch6-08-lock.md) * [6.9. 分布式任务调度系统(TODO)](ch6-cloud/ch6-09-sched.md) * [6.10. 延时任务系统](ch6-cloud/ch6-10-delay-job.md) * [6.12. 补充说明(TODO)](ch6-cloud/ch6-11-faq.md) diff --git a/ch6-cloud/ch6-08-lock.md b/ch6-cloud/ch6-08-lock.md index a8b35e1..831aae5 100644 --- a/ch6-cloud/ch6-08-lock.md +++ b/ch6-cloud/ch6-08-lock.md @@ -74,64 +74,64 @@ println(counter) package main import ( - "sync" + "sync" ) // Lock try lock type Lock struct { - c chan struct{} + c chan struct{} } // NewLock generate a try lock func NewLock() Lock { - var l Lock - l.c = make(chan struct{}, 1) - l.c <- struct{}{} - return l + var l Lock + l.c = make(chan struct{}, 1) + l.c <- struct{}{} + return l } // Lock try lock, return lock result func (l Lock) Lock() bool { - lockResult := false - select { - case <-l.c: - lockResult = true - default: - } - return lockResult + lockResult := false + select { + case <-l.c: + lockResult = true + default: + } + return lockResult } // Unlock , Unlock the try lock func (l Lock) Unlock() bool { - unlockResult := false - select { - case l.c <- struct{}{}: - unlockResult = true - default: - } - return unlockResult + unlockResult := false + select { + case l.c <- struct{}{}: + unlockResult = true + default: + } + return unlockResult } var counter int func main() { - var l = NewLock() - var wg sync.WaitGroup - for i := 0; i < 10; i++ { - wg.Add(1) - go func() { - defer wg.Done() - if !l.Lock() { - // log error - println("lock failed") - return - } - counter++ - println("current counter", counter) - l.Unlock() - }() - } - wg.Wait() + var l = NewLock() + var wg sync.WaitGroup + for i := 0; i < 10; i++ { + wg.Add(1) + go func() { + defer wg.Done() + if !l.Lock() { + // log error + println("lock failed") + return + } + counter++ + println("current counter", counter) + l.Unlock() + }() + } + wg.Wait() } ```