trylock.go 457 B

123456789101112131415161718192021222324
  1. package client
  2. import (
  3. "sync/atomic"
  4. )
  5. // TryLock implement the classic "try-lock" operation.
  6. type TryLock struct {
  7. n int32
  8. }
  9. // Lock tries to lock the try-lock. If successful, it returns true.
  10. // Otherwise, it returns false immedidately.
  11. func (c *TryLock) Lock() error {
  12. if !atomic.CompareAndSwapInt32(&c.n, 0, 1) {
  13. return errDoubleLock
  14. }
  15. return nil
  16. }
  17. // Unlock unlocks the try-lock.
  18. func (c *TryLock) Unlock() {
  19. atomic.StoreInt32(&c.n, 0)
  20. }