// deadlockDetect tries to find a deadlock condition in the current set of waiting acquirers.
354956
func (c *ConversationLockTab) deadlockDetect(ctx context.Context, trace string, waiters map[string]bool) bool {
	// See if this trace is waiting on any other trace
	waitingOnTrace, ok := c.waits[trace]
	if !ok {
		// If not, no deadlock
		return false
	}
	// If we are waiting on a trace we have already encountered, then we have hit a deadlock
	if waiters[waitingOnTrace] {
		c.Debug(ctx, "deadlockDetect: deadlock detected: trace: %s waitingOnTrace: %s waiters: %v",
			trace, waitingOnTrace, waiters)
		return true
	}
	// Set the current trace as waiting, and then continue down the chain
	waiters[trace] = true
	return c.deadlockDetect(ctx, waitingOnTrace, waiters)
}
1275988
func (dm *DRWMutex) Unlock() {

	// create temp array on stack
	locks := make([]string, dm.clnt.dNodeCount)

	{
		dm.m.Lock()
		defer dm.m.Unlock()

		// Check if minimally a single bool is set in the writeLocks array
		lockFound := false
		for _, uid := range dm.writeLocks {
			if isLocked(uid) {
				lockFound = true
				break
			}
		}
		if !lockFound {
			panic("Trying to Unlock() while no Lock() is active")
		}

		// Copy write locks to stack array
		copy(locks, dm.writeLocks[:])
		// Clear write locks array
		dm.writeLocks = make([]string, dm.clnt.dNodeCount)
	}

	isReadLock := false
	unlock(dm.clnt, locks, dm.Name, isReadLock)
}
340066
func (b *BaseKvdb) GetLockTimeout() time.Duration {
	b.lock.Lock()
	defer b.lock.Unlock()
	return b.LockTimeout
}
438083
func (l *FileLock) TryExclusiveLock() error {
	err := syscall.Flock(l.fd, syscall.LOCK_EX|syscall.LOCK_NB)
	if err == syscall.EWOULDBLOCK {
		err = ErrLocked
	}
	return err
}
126995
func (s *SQLStore) GetExclusiveLock() (bool, error) {
	s.Lock()
	defer s.Unlock()
	if s.closed {
		return false, nil
	}
	if s.dbLock == nil {
		s.dbLock = &sqlDBLock{
			id: nuid.Next(),
			db: s.db,
		}
	}
	if s.dbLock.isOwner {
		return true, nil
	}
	hasLock, id, tick, err := s.acquireDBLock(false)
	if err != nil {
		return false, err
	}
	if !hasLock {
		// We did not get the lock. Try to see if the table is updated
		// after 1 interval. If so, consider the lock "healthy" and just
		// return that we did not get the lock. If after a configured
		// number of tries the tick for current owner is not updated,
		// steal the lock.
		prevID := id
		prevTick := tick
		for i := 0; i < sqlLockLostCount; i++ {
			time.Sleep(time.Duration(1.5 * float64(sqlLockUpdateInterval)))
			hasLock, id, tick, err = s.acquireDBLock(false)
			if hasLock || err != nil || id != prevID || tick != prevTick {
				return hasLock, err
			}
			prevTick = tick
		}
		// Try to steal.
		hasLock, _, _, err = s.acquireDBLock(true)
	}
	if hasLock {
		// Success. Keep track that we own the lock so we can clear
		// the table on clean shutdown to release the lock immediately.
		s.dbLock.Lock()
		s.dbLock.isOwner = true
		s.wg.Add(1)
		go s.updateDBLock()
		s.dbLock.Unlock()
	}
	return hasLock, err
}
243081
func (md *MDServerRemote) signalObserverLocked(observerChan chan<- error, id tlf.ID, err error) {
	if observerChan != nil {
		observerChan <- err
		close(observerChan)
	}
	delete(md.observers, id)
}
691397
func (db *DB) DisableConnFail() {
	db.mu.Lock()
	defer db.mu.Unlock()
	db.isConnFail = false
}
416580
func (f *FastTeamChainLoader) loadLocked(m libkb.MetaContext, arg fastLoadArg) (res *fastLoadRes, err error) {

	state := f.findStateInCache(m, arg.ID)

	var shoppingList shoppingList
	if state != nil {
		f.computeWithPreviousState(m, &shoppingList, arg, state)
		if shoppingList.isEmpty() {
			return f.toResult(m, arg, state)
		}
	} else {
		shoppingList.computeFreshLoad(m, arg)
	}

	m.Debug("FastTeamChainLoader#loadLocked: computed shopping list: %+v", shoppingList)

	var newState *keybase1.FastTeamData
	newState, err = f.refresh(m, arg, state, shoppingList)
	if err != nil {
		return nil, err
	}

	// If newState == nil, that means that no updates were required, and the old state
	// is fine, we just need to update the cachedAt time. If newState is non-nil,
	// then we use if for our state going forward.
	if newState == nil {
		setCachedAtToNow(m, state)
	} else {
		state = newState
	}
	// Always update the cache, even if we're just bumping the cachedAt time.
	f.updateCache(m, state)

	return f.toResult(m, arg, state)
}
899610
func (m *Mutex) TryLock() bool {
	v := atomic.LoadInt32(&m.v)
	if v <= 0 {
		return false
	}
	return atomic.CompareAndSwapInt32(&m.v, 1, 0)
}
33735
func (v delegatingStrategy) doConflictDetect(e apply.Element) error {
	if v.options.FailOnConflict {
		if e, ok := e.(apply.ConflictDetector); ok {
			return e.HasConflict()
		}
	}
	return nil
}
316725
func (rw LeveledRWMutex) AssertUnlocked(lockState *LockState) {
	et := lockState.getExclusionType(rw.level)
	if et != nonExclusion {
		panic(unexpectedExclusionError{
			levelToString: lockState.levelToString,
			level:         rw.level,
			exclusionType: et,
		})
	}
}
107968
func (ld *etcdLockDescriptor) Check(ctx context.Context) error {
	_, err := ld.s.cli.KeepAliveOnce(ctx, ld.leaseID)
	if err != nil {
		return convertError(err, "lease")
	}
	return nil
}
675787
func (t *TxStateChange) CheckAndSet() {
	t.c.txStateMu.Lock()
	defer t.c.txStateMu.Unlock()
	defer func() { t.done = true }()

	if t.done {
		panic("CheckAndSet should only be called once")
	}

	if !t.tx && t.c.TransactionActive() && t.c.TxStartedAt.IsZero() {
		t.c.TxStartedAt = time.Now()
	} else if t.tx && !t.c.TransactionActive() && !t.c.TxStartedAt.IsZero() {
		t.c.TxStartedAt = time.Time{}
	}
}
74977
func (nm *NamedMutex) TryLockTimeout(name string, timeout time.Duration) bool {
	nm.localMutex.Lock()
	mc, ok := nm.mutexMap[name]
	if !ok {
		mc = make(chan struct{}, 1)
		nm.mutexMap[name] = mc
	}
	nm.localMutex.Unlock()
	select {
	case mc <- struct{}{}:
		return true
	case <-time.After(timeout):
		return false
	}
}
78358
func (l *Lock) monitorLock(session string, stopCh chan struct{}) {
	defer close(stopCh)
	kv := l.c.KV()
	opts := &QueryOptions{RequireConsistent: true}
WAIT:
	retries := l.opts.MonitorRetries
RETRY:
	pair, meta, err := kv.Get(l.opts.Key, opts)
	if err != nil {
		// If configured we can try to ride out a brief Consul unavailability
		// by doing retries. Note that we have to attempt the retry in a non-
		// blocking fashion so that we have a clean place to reset the retry
		// counter if service is restored.
		if retries > 0 && IsRetryableError(err) {
			time.Sleep(l.opts.MonitorRetryTime)
			retries--
			opts.WaitIndex = 0
			goto RETRY
		}
		return
	}
	if pair != nil && pair.Session == session {
		opts.WaitIndex = meta.LastIndex
		goto WAIT
	}
}
1268176
func (l *lock) IsLocked() bool {
	l.mutex.Lock()
	defer l.mutex.Unlock()
	return l.locked
}
1254962
func (b *BaseKvdb) CheckLockTimeout(
	key string,
	startTime time.Time,
	lockTimeout time.Duration,
) {
	b.lock.Lock()
	defer b.lock.Unlock()
	if lockTimeout > 0 && time.Since(startTime) > lockTimeout {
		b.lockTimedout(key)
	}
}