mirror of
https://github.com/chai2010/advanced-go-programming-book.git
synced 2025-05-24 04:22:22 +00:00
update catalog
This commit is contained in:
parent
3e5a7f41e1
commit
57bf0191a4
@ -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)
|
||||
|
@ -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()
|
||||
}
|
||||
|
||||
```
|
||||
|
Loading…
x
Reference in New Issue
Block a user