lock.go 478 B

12345678910111213141516171819202122232425262728293031323334
  1. package lock
  2. // Lock try lock
  3. type Lock struct {
  4. c chan struct{}
  5. }
  6. // NewLock generate a try lock
  7. func NewLock() Lock {
  8. var l Lock
  9. l.c = make(chan struct{}, 1)
  10. l.c <- struct{}{}
  11. return l
  12. }
  13. // Lock try lock, return lock result
  14. func (l Lock) Lock() bool {
  15. lockResult := false
  16. select {
  17. case <-l.c:
  18. lockResult = true
  19. default:
  20. }
  21. return lockResult
  22. }
  23. // Unlock , Unlock the try lock
  24. func (l Lock) Unlock() {
  25. l.c <- struct{}{}
  26. }
  27. func (l Lock) Close() {
  28. close(l.c)
  29. }