// All following functions assume the lock is already grabbed
330705
func (c *ToxicCollection) findToxicByName(name string) *toxics.ToxicWrapper {
	for dir := range c.chain {
		for i, toxic := range c.chain[dir] {
			if i == 0 {
				// Skip the first noop toxic, it has no name
				continue
			}
			if toxic.Name == name {
				return toxic
			}
		}
	}
	return nil
}
287231
func (f *FileLock) TryLock() error {
	return f.performLock(syscall.LOCK_EX | syscall.LOCK_NB)
}
1012789
func (l *lockTracker) Lock(id string) {
	l.seenMu.RLock()
	if _, seen := l.seen[id]; !seen {
		l.seenMu.RUnlock()
		l.seenMu.Lock()
		l.seen[id] = struct{}{}
		l.seenMu.Unlock()
	} else {
		l.seenMu.RUnlock()
	}

	l.Locker.Lock(id)
}
562907
func (l *locker) Lock(s statemgr.Locker, reason string) error {
	l.mu.Lock()
	defer l.mu.Unlock()

	l.state = s

	ctx, cancel := context.WithTimeout(l.ctx, l.timeout)
	defer cancel()

	lockInfo := state.NewLockInfo()
	lockInfo.Operation = reason

	err := slowmessage.Do(LockThreshold, func() error {
		id, err := statemgr.LockWithContext(ctx, s, lockInfo)
		l.lockID = id
		return err
	}, func() {
		if l.ui != nil {
			l.ui.Output(l.color.Color(LockMessage))
		}
	})

	if err != nil {
		return errwrap.Wrapf(strings.TrimSpace(LockErrorMessage), err)
	}

	return nil
}
600123
func (s *GlobalStore) lock(addr common.Address, key []byte) (unlock func(), err error) {
	start := time.Now()
	nodeLockKey := addr.Hex()
	for {
		_, loaded := s.nodesLocks.LoadOrStore(nodeLockKey, struct{}{})
		if !loaded {
			break
		}
		time.Sleep(lockCheckDelay)
		if time.Since(start) > lockTimeout {
			return nil, errLockTimeout
		}
	}
	start = time.Now()
	keyLockKey := common.Bytes2Hex(key)
	for {
		_, loaded := s.keysLocks.LoadOrStore(keyLockKey, struct{}{})
		if !loaded {
			break
		}
		time.Sleep(lockCheckDelay)
		if time.Since(start) > lockTimeout {
			return nil, errLockTimeout
		}
	}
	return func() {
		s.nodesLocks.Delete(nodeLockKey)
		s.keysLocks.Delete(keyLockKey)
	}, nil
}
282100
func acquireLockForSocket(addr *net.UnixAddr) *flock.Flock {
	lockname := fmt.Sprintf("%s.lock", addr.String())
	lock := flock.NewFlock(lockname)
	locked, err := lock.TryLock()
	if err != nil {
		panic(fmt.Sprintf("Could not acquire the lock %q to listen on %v: %v", lockname, addr, err))
	}
	if !locked {
		panic(fmt.Sprintf("Lock file %q for %v is in use by another process already", lockname, addr))
	}
	// We have the exclusive use of the socket, clear away any old sockets and listen:
	_ = os.Remove(addr.String())
	return lock
}
483064
func (m *Mutex) Lock() {
	// Uncontended case.
	if atomic.AddInt32(&m.v, -1) == 0 {
		return
	}

	for {
		// Try to acquire the mutex again, at the same time making sure
		// that m.v is negative, which indicates to the owner of the
		// lock that it is contended, which will force it to try to wake
		// someone up when it releases the mutex.
		if v := atomic.LoadInt32(&m.v); v >= 0 && atomic.SwapInt32(&m.v, -1) == 1 {
			return
		}

		// Wait for the mutex to be released before trying again.
		<-m.ch
	}
}
349869
func (l *FileLock) ExclusiveLock() error {
	return syscall.Flock(l.fd, syscall.LOCK_EX)
}
1117529
func (i *Issue) GetLocked() bool {
	if i == nil || i.Locked == nil {
		return false
	}
	return *i.Locked
}
810333
func (l *lock) Lock(ctx context.Context) error {
	l.mutex.Lock()
	defer l.mutex.Unlock()

	if l.locked {
		return driver.WithStack(AlreadyLockedError)
	}

	// Try to claim lock
	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()
	if err := l.api.WriteKeyIfEmpty(ctx, l.key, l.id, l.ttl); err != nil {
		if driver.IsPreconditionFailed(err) {
			return driver.WithStack(AlreadyLockedError)
		}
		return driver.WithStack(err)
	}

	// Success
	l.locked = true

	// Keep renewing
	renewCtx, renewCancel := context.WithCancel(context.Background())
	go l.renewLock(renewCtx)
	l.cancelRenewal = renewCancel

	return nil
}
91099
func (l *Lock) Unlock() error {
	defer metrics.MeasureSince(metricLockUnlock, time.Now())

	l.lock.Lock()
	defer l.lock.Unlock()
	if !l.held {
		return nil
	}

	// Stop any existing locking or renewal attempts
	l.stopLock.Lock()
	if !l.stopped {
		l.stopped = true
		close(l.stopCh)
	}
	l.stopLock.Unlock()

	// Read the record value before deleting. This needs to be a CAS operation or
	// else we might be deleting someone else's lock.
	ctx := context.Background()
	r, err := l.get(ctx)
	if err != nil {
		return errwrap.Wrapf("failed to read lock for deletion: {{err}}", err)
	}
	if r != nil && r.Identity == l.identity {
		ctx := context.Background()
		conds := storage.Conditions{
			GenerationMatch:     r.attrs.Generation,
			MetagenerationMatch: r.attrs.Metageneration,
		}

		obj := l.backend.client.Bucket(l.backend.bucket).Object(l.key)
		if err := obj.If(conds).Delete(ctx); err != nil {
			// If the pre-condition failed, it means that someone else has already
			// acquired the lock and we don't want to delete it.
			if terr, ok := err.(*googleapi.Error); ok && terr.Code == 412 {
				l.backend.logger.Debug("unlock: preconditions failed (lock already taken by someone else?)")
			} else {
				return errwrap.Wrapf("failed to delete lock: {{err}}", err)
			}
		}
	}

	// We are no longer holding the lock
	l.held = false

	return nil
}
730113
func (m *MutexKV) Lock(key string) {
	log.Printf("[DEBUG] Locking %q", key)
	m.get(key).Lock()
	log.Printf("[DEBUG] Locked %q", key)
}
15879
func (lk *etcdLock) waitForLock() {
	// If timeout is not specified, set it to high value
	timeoutIntvl := time.Second * time.Duration(20000)
	if lk.timeout != 0 {
		timeoutIntvl = time.Second * time.Duration(lk.timeout)
	}

	log.Infof("Waiting to acquire lock (%s/%s)", lk.name, lk.myID)

	// Create a timer
	timer := time.NewTimer(timeoutIntvl)
	defer timer.Stop()

	// Wait for changes
	for {
		// wait on watch channel for holder to release the lock
		select {
		case <-timer.C:
			lk.mutex.Lock()
			if lk.timeout != 0 {
				lk.mutex.Unlock()
				log.Infof("Lock timeout on lock %s/%s", lk.name, lk.myID)

				lk.eventChan <- LockEvent{EventType: LockAcquireTimeout}

				log.Infof("Lock acquire timed out. Stopping lock")

				lk.watchCancel()

				// Release the lock
				lk.Release()

				return
			}
			lk.mutex.Unlock()
		case watchResp := <-lk.watchCh:
			if watchResp != nil {
				log.Debugf("Received watch notification(%s/%s): %+v", lk.name, lk.myID, watchResp)

				if watchResp.Action == "expire" || watchResp.Action == "delete" ||
					watchResp.Action == "compareAndDelete" {
					log.Infof("Retrying to acquire lock")
					return
				}
			}
		case <-lk.stopChan:
			log.Infof("Stopping lock")
			lk.watchCancel()
			return
		}
	}
}
437408
func (mutex *Mutex) Lock() error {
	ret := int(C.SDL_LockMutex(mutex.cptr()))
	if ret != 0 {
		return GetError()
	}
	return nil
}
59172
func lock() error {
	var err error
	var lock lockfile.Lockfile

	daemonMutex.Lock()
	lock, err = getLockfile()
	if err != nil {
		daemonMutex.Unlock()
		return fmt.Errorf("[lock] cannot init lockfile: %v", err)
	}

	// Try to acquire the lock and in case of a temporary error, sleep for
	// two seconds until the next retry (at most 10 times).  Return fatal
	// errors immediately, as we can't recover.
	for i := 0; i < 10; i++ {
		if err = lock.TryLock(); err != nil {
			switch err.(type) {
			case lockfile.TemporaryError:
				logrus.Debugf("[lock] busy: next retry in two seconds")
				time.Sleep(2 * time.Second)
			default:
				daemonMutex.Unlock()
				return fmt.Errorf("[lock] error acquiring lock: %s", err)
			}
		}
	}
	if err != nil {
		daemonMutex.Unlock()
		return fmt.Errorf("[lock] error acquiring lock: too many tries")
	}

	logrus.Debugf("[lock] lock acquired")
	return nil
}
459535
func (f *Flock) Locked() bool {
	f.m.RLock()
	defer f.m.RUnlock()
	return f.l
}
1239551
func (client *lockRESTClient) Unlock(args dsync.LockArgs) (reply bool, err error) {
	return client.restCall(lockRESTMethodUnlock, args)
}