1
0
mirror of https://github.com/chai2010/advanced-go-programming-book.git synced 2025-05-24 12:32:21 +00:00

update catalog

This commit is contained in:
Xargin 2018-08-01 13:15:52 +08:00
parent 3e5a7f41e1
commit 57bf0191a4
2 changed files with 38 additions and 38 deletions

View File

@ -60,7 +60,7 @@
* [6.5. 分布式缓存(TODO)](ch6-cloud/ch6-05-cache.md) * [6.5. 分布式缓存(TODO)](ch6-cloud/ch6-05-cache.md)
* [6.6. etcd(TODO)](ch6-cloud/ch6-06-etcd.md) * [6.6. etcd(TODO)](ch6-cloud/ch6-06-etcd.md)
* [6.7. 分布式 id 生成器](ch6-cloud/ch6-07-dist-id.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.9. 分布式任务调度系统(TODO)](ch6-cloud/ch6-09-sched.md)
* [6.10. 延时任务系统](ch6-cloud/ch6-10-delay-job.md) * [6.10. 延时任务系统](ch6-cloud/ch6-10-delay-job.md)
* [6.12. 补充说明(TODO)](ch6-cloud/ch6-11-faq.md) * [6.12. 补充说明(TODO)](ch6-cloud/ch6-11-faq.md)

View File

@ -74,64 +74,64 @@ println(counter)
package main package main
import ( import (
"sync" "sync"
) )
// Lock try lock // Lock try lock
type Lock struct { type Lock struct {
c chan struct{} c chan struct{}
} }
// NewLock generate a try lock // NewLock generate a try lock
func NewLock() Lock { func NewLock() Lock {
var l Lock var l Lock
l.c = make(chan struct{}, 1) l.c = make(chan struct{}, 1)
l.c <- struct{}{} l.c <- struct{}{}
return l return l
} }
// Lock try lock, return lock result // Lock try lock, return lock result
func (l Lock) Lock() bool { func (l Lock) Lock() bool {
lockResult := false lockResult := false
select { select {
case <-l.c: case <-l.c:
lockResult = true lockResult = true
default: default:
} }
return lockResult return lockResult
} }
// Unlock , Unlock the try lock // Unlock , Unlock the try lock
func (l Lock) Unlock() bool { func (l Lock) Unlock() bool {
unlockResult := false unlockResult := false
select { select {
case l.c <- struct{}{}: case l.c <- struct{}{}:
unlockResult = true unlockResult = true
default: default:
} }
return unlockResult return unlockResult
} }
var counter int var counter int
func main() { func main() {
var l = NewLock() var l = NewLock()
var wg sync.WaitGroup var wg sync.WaitGroup
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
wg.Add(1) wg.Add(1)
go func() { go func() {
defer wg.Done() defer wg.Done()
if !l.Lock() { if !l.Lock() {
// log error // log error
println("lock failed") println("lock failed")
return return
} }
counter++ counter++
println("current counter", counter) println("current counter", counter)
l.Unlock() l.Unlock()
}() }()
} }
wg.Wait() wg.Wait()
} }
``` ```