You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
29 lines
359 B
29 lines
359 B
2 years ago
|
package golock
|
||
|
|
||
|
type Lock struct {
|
||
|
c chan struct{}
|
||
|
}
|
||
|
|
||
|
func NewLock() Lock {
|
||
|
l := Lock{}
|
||
|
l.c = make(chan struct{}, 1)
|
||
|
l.c <- struct{}{}
|
||
|
return l
|
||
|
}
|
||
|
|
||
|
// Lock 上锁
|
||
|
func (l *Lock) Lock() bool {
|
||
|
lockResult := false
|
||
|
select {
|
||
|
case <-l.c:
|
||
|
lockResult = true
|
||
|
default:
|
||
|
}
|
||
|
return lockResult
|
||
|
}
|
||
|
|
||
|
// Unlock 解锁
|
||
|
func (l *Lock) Unlock() {
|
||
|
l.c <- struct{}{}
|
||
|
}
|