// Lock obtains the advisory lock.
429886
func (l *AdvisoryLock) Lock() error {
	l.mu.Lock()
	defer l.mu.Unlock()

	if l.commited {
		panic("lock called on commited lock")
	}

	if l.LockTimeout != 0 {
		_, err := l.tx.Exec(fmt.Sprintf("SET LOCAL lock_timeout = %d", int(l.LockTimeout.Seconds()*1000)))
		if err != nil {
			return fmt.Errorf("error setting lock timeout: %v", err)
		}
	}

	_, err := l.tx.Exec(fmt.Sprintf("SELECT pg_advisory_lock($1) /* %s */", l.Context), l.key)
	if err != nil {
		// If there's an error trying to obtain the lock, probably the
		// safest thing to do is commit the transaction and make this
		// lock invalid.
		l.commit()

		if err, ok := err.(*pq.Error); ok {
			switch err.Code.Name() {
			case "query_canceled":
				return Canceled
			case "lock_not_available":
				return ErrLockTimeout
			}
		}

		return fmt.Errorf("error obtaining lock: %v", err)
	}

	l.c += 1

	return nil
}
217980
func (query Query) Lock(lock ...string) Query {
	if !query.repo.inTransaction {
		return query
	}

	if len(lock) > 0 {
		query.LockClause = lock[0]
	} else {
		query.LockClause = "FOR UPDATE"
	}

	return query
}
41968
func (w *walker) lock(v reflect.Value) {
	if !w.useLocks {
		return
	}

	if !v.IsValid() || !v.CanInterface() {
		return
	}

	type rlocker interface {
		RLocker() sync.Locker
	}

	var locker sync.Locker

	// We can't call Interface() on a value directly, since that requires
	// a copy. This is OK, since the pointer to a value which is a sync.Locker
	// is also a sync.Locker.
	if v.Kind() == reflect.Ptr {
		switch l := v.Interface().(type) {
		case rlocker:
			// don't lock a mutex directly
			if _, ok := l.(*sync.RWMutex); !ok {
				locker = l.RLocker()
			}
		case sync.Locker:
			locker = l
		}
	} else if v.CanAddr() {
		switch l := v.Addr().Interface().(type) {
		case rlocker:
			// don't lock a mutex directly
			if _, ok := l.(*sync.RWMutex); !ok {
				locker = l.RLocker()
			}
		case sync.Locker:
			locker = l
		}
	}

	// still no callable locker
	if locker == nil {
		return
	}

	// don't lock a mutex directly
	switch locker.(type) {
	case *sync.Mutex, *sync.RWMutex:
		return
	}

	locker.Lock()
	w.locks[w.depth] = locker
}
1332132
func (c *TeeConn) Lock(ctx context.Context, dirPath, contents string) (topo.LockDescriptor, error) {
	// Lock lockFirst.
	fLD, err := c.lockFirst.Lock(ctx, dirPath, contents)
	if err != nil {
		return nil, err
	}

	// Lock lockSecond.
	sLD, err := c.lockSecond.Lock(ctx, dirPath, contents)
	if err != nil {
		if err := fLD.Unlock(ctx); err != nil {
			log.Warningf("Failed to unlock lockFirst after failed lockSecond lock for %v: %v", dirPath, err)
		}
		return nil, err
	}

	// Remember both locks in teeTopoLockDescriptor.
	return &teeTopoLockDescriptor{
		c:                    c,
		dirPath:              dirPath,
		firstLockDescriptor:  fLD,
		secondLockDescriptor: sLD,
	}, nil
}
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
}
237623
func (l *Lock) Unlock() error {
	// Hold the lock as we try to release
	l.l.Lock()
	defer l.l.Unlock()

	// Ensure the lock is actually held
	if !l.isHeld {
		return ErrLockNotHeld
	}

	// Set that we no longer own the lock
	l.isHeld = false

	// Stop the session renew
	if l.sessionRenew != nil {
		defer func() {
			close(l.sessionRenew)
			l.sessionRenew = nil
		}()
	}

	// Get the lock entry, and clear the lock session
	lockEnt := l.lockEntry(l.lockSession)
	l.lockSession = ""

	// Release the lock explicitly
	kv := l.c.KV()
	_, _, err := kv.Release(lockEnt, nil)
	if err != nil {
		return fmt.Errorf("failed to release lock: %v", err)
	}
	return nil
}
661286
func (zm *zMutex) Lock(desc string) error {
	return zm.LockWithTimeout(365*24*time.Hour, desc)
}
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
}
1270650
func (r *remoteClient) Lock(info *state.LockInfo) (string, error) {
	ctx := context.Background()

	lockErr := &state.LockError{Info: r.lockInfo}

	// Lock the workspace.
	_, err := r.client.Workspaces.Lock(ctx, r.workspace.ID, tfe.WorkspaceLockOptions{
		Reason: tfe.String("Locked by Terraform"),
	})
	if err != nil {
		if err == tfe.ErrWorkspaceLocked {
			err = fmt.Errorf("%s (lock ID: \"%s/%s\")", err, r.organization, r.workspace.Name)
		}
		lockErr.Err = err
		return "", lockErr
	}

	r.lockInfo = info

	return r.lockInfo.ID, nil
}
736698
func (l *AddrLocker) lock(address common.Address) *sync.Mutex {
	l.mu.Lock()
	defer l.mu.Unlock()
	if l.locks == nil {
		l.locks = make(map[common.Address]*sync.Mutex)
	}
	if _, ok := l.locks[address]; !ok {
		l.locks[address] = new(sync.Mutex)
	}
	return l.locks[address]
}
451798
func (l *lockfile) lock(l_type int16) {
	lk := unix.Flock_t{
		Type:   l_type,
		Whence: int16(os.SEEK_SET),
		Start:  0,
		Len:    0,
	}
	switch l_type {
	case unix.F_RDLCK:
		l.rwMutex.RLock()
	case unix.F_WRLCK:
		l.rwMutex.Lock()
	default:
		panic(fmt.Sprintf("attempted to acquire a file lock of unrecognized type %d", l_type))
	}
	l.stateMutex.Lock()
	defer l.stateMutex.Unlock()
	if l.counter == 0 {
		// If we're the first reference on the lock, we need to open the file again.
		fd, err := openLock(l.file, l.ro)
		if err != nil {
			panic(fmt.Sprintf("error opening %q", l.file))
		}
		unix.CloseOnExec(fd)
		l.fd = uintptr(fd)

		// Optimization: only use the (expensive) fcntl syscall when
		// the counter is 0.  In this case, we're either the first
		// reader lock or a writer lock.
		for unix.FcntlFlock(l.fd, unix.F_SETLKW, &lk) != nil {
			time.Sleep(10 * time.Millisecond)
		}
	}
	l.locktype = l_type
	l.locked = true
	l.counter++
}
233107
func (l *lockServer) Lock(args *dsync.LockArgs, reply *bool) error {
	l.mutex.Lock()
	defer l.mutex.Unlock()
	_, *reply = l.lockMap[args.Resource]
	if !*reply { // No locks held on the given name, so claim write lock
		l.lockMap[args.Resource] = []lockRequesterInfo{
			{
				writer:        true,
				serverAddr:    args.ServerAddr,
				rpcPath:       args.ServiceEndpoint,
				uid:           args.UID,
				timestamp:     time.Now().UTC(),
				timeLastCheck: time.Now().UTC(),
			},
		}
	}
	*reply = !*reply // Negate *reply to return true when lock is granted or false otherwise
	return nil
}
978534
func (md *MDServerMemory) Lock(ctx context.Context,
	tlfID tlf.ID, lockID keybase1.LockID) error {
	// An RPC-based client would receive a throttle message from the
	// server and retry with backoff, but here we need to implement
	// the retry logic explicitly.
	for {
		ch := md.doLock(ctx, tlfID, lockID)
		if ch == nil {
			return nil
		}
		select {
		// TODO: wait for the clock to pass the expired time.  We'd
		// need a new method in the `Clock` interface to support this.
		case <-ch:
			continue
		case <-ctx.Done():
			return ctx.Err()
		}
	}
}
1168232
func (s *Server) lock(ctx context.Context, nodePath, contents string) (topo.LockDescriptor, error) {
	nodePath = path.Join(s.root, nodePath, locksPath)

	// Get a lease, set its KeepAlive.
	lease, err := s.cli.Grant(ctx, int64(*leaseTTL))
	if err != nil {
		return nil, convertError(err, nodePath)
	}
	leaseKA, err := s.cli.KeepAlive(ctx, lease.ID)
	if err != nil {
		return nil, convertError(err, nodePath)
	}
	go func() {
		// Drain the lease keepAlive channel, we're not
		// interested in its contents.
		for range leaseKA {
		}
	}()

	// Create an ephemeral node in the locks directory.
	key, revision, err := s.newUniqueEphemeralKV(ctx, s.cli, lease.ID, nodePath, contents)
	if err != nil {
		return nil, err
	}

	// Wait until all older nodes in the locks directory are gone.
	for {
		done, err := s.waitOnLastRev(ctx, s.cli, nodePath, revision)
		if err != nil {
			// We had an error waiting on the last node.
			// Revoke our lease, this will delete the file.
			if _, rerr := s.cli.Revoke(context.Background(), lease.ID); rerr != nil {
				log.Warningf("Revoke(%d) failed, may have left %v behind: %v", lease.ID, key, rerr)
			}
			return nil, err
		}
		if done {
			// No more older nodes, we're it!
			return &etcdLockDescriptor{
				s:       s,
				leaseID: lease.ID,
			}, nil
		}
	}
}
893884
func (s *Store) Lock() (err error) {
	s.mtx.Lock()
	defer s.mtx.Unlock()

	if s.flags.watchingOnly {
		return ErrWatchingOnly
	}

	// Remove clear text passphrase from key store.
	if s.isLocked() {
		err = ErrLocked
	} else {
		zero(s.passphrase)
		s.passphrase = nil
		zero(s.secret)
		s.secret = nil
	}

	// Remove clear text private keys from all address entries.
	for _, addr := range s.addrMap {
		if baddr, ok := addr.(*btcAddress); ok {
			_ = baddr.lock()
		}
	}

	return err
}
629046
func (m *Mutex) Lock() error {
	value, err := m.genValueFunc()
	if err != nil {
		return err
	}

	for i := 0; i < m.tries; i++ {
		if i != 0 {
			time.Sleep(m.delayFunc(i))
		}

		start := time.Now()

		n := m.actOnPoolsAsync(func(pool Pool) bool {
			return m.acquire(pool, value)
		})

		until := time.Now().Add(m.expiry - time.Now().Sub(start) - time.Duration(int64(float64(m.expiry)*m.factor)) + 2*time.Millisecond)
		if n >= m.quorum && time.Now().Before(until) {
			m.value = value
			m.until = until
			return nil
		}
		m.actOnPoolsAsync(func(pool Pool) bool {
			return m.release(pool, value)
		})
	}

	return ErrFailed
}
292792
func (r *Registry) WithLock(obj mo.Reference, f func()) {
	if enableLocker {
		mu := r.locker(obj)
		mu.Lock()
		defer mu.Unlock()
	}
	f()
}