// Lock is part of the topo.Conn interface.
488127
func (zs *Server) Lock(ctx context.Context, dirPath, contents string) (topo.LockDescriptor, error) {
	// Lock paths end in a trailing slash to that when we create
	// sequential nodes, they are created as children, not siblings.
	locksDir := path.Join(zs.root, dirPath, locksPath) + "/"

	// Create the locks path, possibly creating the parent.
	nodePath, err := CreateRecursive(ctx, zs.conn, locksDir, []byte(contents), zk.FlagSequence|zk.FlagEphemeral, zk.WorldACL(PermFile), 1)
	if err != nil {
		return nil, convertError(err, locksDir)
	}

	err = obtainQueueLock(ctx, zs.conn, nodePath)
	if err != nil {
		var errToReturn error
		switch err {
		case context.DeadlineExceeded:
			errToReturn = topo.NewError(topo.Timeout, nodePath)
		case context.Canceled:
			errToReturn = topo.NewError(topo.Interrupted, nodePath)
		default:
			errToReturn = vterrors.Wrapf(err, "failed to obtain action lock: %v", nodePath)
		}

		// Regardless of the reason, try to cleanup.
		log.Warningf("Failed to obtain action lock: %v", err)
		zs.conn.Delete(ctx, nodePath, -1)

		// Show the other locks in the directory
		dir := path.Dir(nodePath)
		children, _, err := zs.conn.Children(ctx, dir)
		if err != nil {
			log.Warningf("Failed to get children of %v: %v", dir, err)
			return nil, errToReturn
		}

		if len(children) == 0 {
			log.Warningf("No other locks present, you may just try again now.")
			return nil, errToReturn
		}

		childPath := path.Join(dir, children[0])
		data, _, err := zs.conn.Get(ctx, childPath)
		if err != nil {
			log.Warningf("Failed to get first locks node %v (may have just ended): %v", childPath, err)
			return nil, errToReturn
		}

		log.Warningf("------ Most likely blocking lock: %v\n%v", childPath, string(data))
		return nil, errToReturn
	}

	// Remove the root prefix from the file. So when we delete it,
	// it's a relative file.
	nodePath = nodePath[len(zs.root):]
	return &zkLockDescriptor{
		zs:       zs,
		nodePath: nodePath,
	}, nil
}
711198
func (_m *DistributedLock) Lock(ctx context.Context) error {
	ret := _m.Called(ctx)

	var r0 error
	if rf, ok := ret.Get(0).(func(context.Context) error); ok {
		r0 = rf(ctx)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}
866266
func (i *MySQLLock) Lock() error {
	defer metrics.MeasureSince([]string{"mysql", "get_lock"}, time.Now())

	// Lock timeout math.MaxInt32 instead of -1 solves compatibility issues with
	// different MySQL flavours i.e. MariaDB
	rows, err := i.in.Query("SELECT GET_LOCK(?, ?), IS_USED_LOCK(?)", i.key, math.MaxInt32, i.key)
	if err != nil {
		return err
	}

	defer rows.Close()
	rows.Next()
	var lock sql.NullInt64
	var connectionID sql.NullInt64
	rows.Scan(&lock, &connectionID)

	if rows.Err() != nil {
		return rows.Err()
	}

	// 1 is returned from GET_LOCK if it was able to get the lock
	// 0 if it failed and NULL if some strange error happened.
	// https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_get-lock
	if !lock.Valid || lock.Int64 != 1 {
		return ErrLockHeld
	}

	// Since we have the lock alert the rest of the cluster
	// that we are now the active leader.
	err = i.becomeLeader()
	if err != nil {
		return ErrLockHeld
	}

	// This will return the connection ID of NULL if an error happens
	// https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_is-used-lock
	if !connectionID.Valid {
		return ErrSettingGlobalID
	}

	GlobalLockID = connectionID.Int64

	return nil
}
804901
func (l *Lock) writeLock() (bool, error) {
	// Pooling
	l.backend.permitPool.Acquire()
	defer l.backend.permitPool.Release()

	// Create a transaction to read and the update (maybe)
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// The operation may be retried, so we need to stop it if we lose leadership.
	go func() {
		select {
		case <-l.stopCh:
			cancel()
		case <-ctx.Done():
		}
	}()

	// Build up the list of conditions
	var conds storage.Conditions

	// Read the record
	r, err := l.get(ctx)
	if err != nil {
		return false, errwrap.Wrapf("write lock: {{err}}", err)
	}
	if r != nil {
		// If the key is empty or the identity is ours or the ttl expired, we can
		// write. Otherwise, return now because we cannot.
		if r.Key != "" && r.Identity != l.identity && time.Now().UTC().Sub(r.Timestamp) < l.ttl {
			return false, nil
		}

		// CAS operation
		conds.GenerationMatch = r.attrs.Generation
		conds.MetagenerationMatch = r.attrs.Metageneration
	} else {
		// Ensure no one created while we were working
		conds.DoesNotExist = true
	}

	// Update the lock to now
	lockData, err := json.Marshal(&LockRecord{
		Key:       l.key,
		Value:     l.value,
		Identity:  l.identity,
		Timestamp: time.Now().UTC(),
	})
	if err != nil {
		return false, errwrap.Wrapf("write lock: failed to encode JSON: {{err}}", err)
	}

	// Write the object
	obj := l.backend.client.Bucket(l.backend.bucket).Object(l.key)
	w := obj.If(conds).NewWriter(ctx)
	w.ObjectAttrs.CacheControl = "no-cache; no-store; max-age=0"
	w.ObjectAttrs.Metadata = map[string]string{
		"lock": string(lockData),
	}
	if err := w.Close(); err != nil {
		// If the pre-condition failed, it means that we already have a lock.
		if terr, ok := err.(*googleapi.Error); ok && terr.Code == 412 {
			return false, nil
		}
		return false, err
	}

	return true, nil
}
216096
func (l *lockfile) Locked() bool {
	l.stateMutex.Lock()
	defer l.stateMutex.Unlock()
	return l.locked && (l.locktype == unix.F_WRLCK)
}
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
}
437408
func (mutex *Mutex) Lock() error {
	ret := int(C.SDL_LockMutex(mutex.cptr()))
	if ret != 0 {
		return GetError()
	}
	return nil
}
582585
func (m *RWMutex) Lock() {
	var caller string
	if _, file, line, ok := runtime.Caller(1); ok {
		caller = fmt.Sprintf("%s:%d", file, line)
	}
	if m.log {
		astilog.Debugf("Requesting lock for %s at %s", m.name, caller)
	}
	m.mutex.Lock()
	if m.log {
		astilog.Debugf("Lock acquired for %s at %s", m.name, caller)
	}
	m.lastSuccessfulLockCaller = caller
}
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
}
431347
func (l *Locker) Lock(name string) {
	l.mu.Lock()
	if l.locks == nil {
		l.locks = make(map[string]*lockCtr)
	}

	nameLock, exists := l.locks[name]
	if !exists {
		nameLock = &lockCtr{}
		l.locks[name] = nameLock
	}

	// increment the nameLock waiters while inside the main mutex
	// this makes sure that the lock isn't deleted if `Lock` and `Unlock` are called concurrently
	nameLock.inc()
	l.mu.Unlock()

	// Lock the nameLock outside the main mutex so we don't block other operations
	// once locked then we can decrement the number of waiters for this lock
	nameLock.Lock()
	nameLock.dec()
}
282441
func (f *File) Lock() (err error) {
	done := make(chan struct{})
	f.fs.sendEvents(FSEvent{
		EventType: FSEventLock,
		File:      f,
		Done:      done,
	})
	defer close(done)
	f.lockedLock.Lock()
	defer f.lockedLock.Unlock()
	if f.locked {
		return nil
	}
	defer func() {
		if err == nil {
			f.locked = true
		}
	}()

	// First, sync all and ask journal to flush all existing writes.
	err = f.fs.SyncAll()
	if err != nil {
		return err
	}
	jManager, err := libkbfs.GetJournalManager(f.fs.config)
	if err != nil {
		return err
	}
	if err = jManager.FinishSingleOp(f.fs.ctx,
		f.fs.root.GetFolderBranch().Tlf, nil, f.fs.priority); err != nil {
		return err
	}

	// Now, sync up with the server, while making sure a lock is held by us. If
	// lock taking fails, RPC layer retries automatically.
	lockID := f.getLockID()
	return f.fs.config.KBFSOps().SyncFromServer(f.fs.ctx,
		f.fs.root.GetFolderBranch(), &lockID)
}
730113
func (m *MutexKV) Lock(key string) {
	log.Printf("[DEBUG] Locking %q", key)
	m.get(key).Lock()
	log.Printf("[DEBUG] Locked %q", key)
}
1004820
func funlock(db *DB) error {
	var lock syscall.Flock_t
	lock.Start = 0
	lock.Len = 0
	lock.Type = syscall.F_UNLCK
	lock.Whence = 0
	return syscall.FcntlFlock(uintptr(db.file.Fd()), syscall.F_SETLK, &lock)
}
3587
func (m *RWMutex) Lock() {
	atomic.AddInt64(&m.pendingWriters, 1)
	m.mutex.Lock()
	atomic.AddInt64(&m.writers, 1)
	atomic.AddInt64(&m.pendingWriters, -1)

	stackBufLen := RWMutexStackBufferLength()

	m.stateMutex.Lock()
	if len(m.stackBuf) < stackBufLen {
		m.stackBuf = make([]byte, stackBufLen)
	}
	n := runtime.Stack(m.stackBuf, false)
	m.lastLockStack = m.stackBuf[:n]
	m.stateMutex.Unlock()
}
1321944
func (f *LockPIDFile) Lock() (err error) {
	pathp, err := syscall.UTF16PtrFromString(f.name)
	if err != nil {
		return PIDFileLockError{f.name}
	}
	access := uint32(syscall.GENERIC_READ | syscall.GENERIC_WRITE)
	createmode := uint32(syscall.OPEN_ALWAYS)
	sharemode := uint32(syscall.FILE_SHARE_READ) // os.Open always uses FILE_SHARE_READ | FILE_SHARE_WRITE
	var sa *syscall.SecurityAttributes
	r, err := syscall.CreateFile(pathp, access, sharemode, sa, createmode, syscall.FILE_ATTRIBUTE_NORMAL, 0)
	if err != nil {
		return PIDFileLockError{f.name}
	}
	// this is what os.openFile does
	f.file = os.NewFile(uintptr(r), f.name)

	pid := os.Getpid()
	fmt.Fprintf(f.file, "%d", pid)
	f.file.Sync()

	f.G().Log.Debug("Locked pidfile %s for pid=%d", f.name, pid)

	return nil
}
814651
func (c *LockCache) Locks() []Lock {
	var locks []Lock
	c.kv.Visit(func(key string, val interface{}) bool {
		// Only report file->id entries not reverse
		if !c.isIdKey(key) {
			lock := val.(*Lock)
			locks = append(locks, *lock)
		}
		return true // continue
	})
	return locks
}
767201
func (a *btcAddress) lock() error {
	if !a.flags.encrypted {
		return errors.New("unable to lock unencrypted address")
	}

	zero(a.privKeyCT)
	a.privKeyCT = nil
	return nil
}