// lockBlocking will try to acquire either a read or a write lock
//
// The function will loop using a built-in timing randomized back-off
// algorithm until either the lock is acquired successfully or more
// time has elapsed than the timeout value.
493355
func (dm *DRWMutex) lockBlocking(timeout time.Duration, id, source string, isReadLock bool) (locked bool) {
	doneCh, start := make(chan struct{}), time.Now().UTC()
	defer close(doneCh)

	// Use incremental back-off algorithm for repeated attempts to acquire the lock
	for range newRetryTimerSimple(doneCh) {
		// Create temp array on stack.
		locks := make([]string, dm.clnt.dNodeCount)

		// Try to acquire the lock.
		success := lock(dm.clnt, &locks, dm.Name, id, source, isReadLock)
		if success {
			dm.m.Lock()
			defer dm.m.Unlock()

			// If success, copy array to object
			if isReadLock {
				// Append new array of strings at the end
				dm.readersLocks = append(dm.readersLocks, make([]string, dm.clnt.dNodeCount))
				// and copy stack array into last spot
				copy(dm.readersLocks[len(dm.readersLocks)-1], locks[:])
			} else {
				copy(dm.writeLocks, locks[:])
			}

			return true
		}
		if time.Now().UTC().Sub(start) >= timeout { // Are we past the timeout?
			break
		}
		// Failed to acquire the lock on this attempt, incrementally wait
		// for a longer back-off time and try again afterwards.
	}
	return false
}
987068
func (l *lockRESTServer) LockHandler(w http.ResponseWriter, r *http.Request) {
	if !l.IsValid(w, r) {
		l.writeErrorResponse(w, errors.New("Invalid request"))
		return
	}

	ctx := newContext(r, w, "Lock")

	var lockArgs dsync.LockArgs
	if r.ContentLength < 0 {
		l.writeErrorResponse(w, errInvalidArgument)
		return
	}

	err := gob.NewDecoder(r.Body).Decode(&lockArgs)
	if err != nil {
		l.writeErrorResponse(w, err)
		return
	}

	success, err := l.ll.Lock(lockArgs)
	if err != nil {
		l.writeErrorResponse(w, err)
		return
	}
	resp := lockResponse{Success: success}
	logger.LogIf(ctx, gob.NewEncoder(w).Encode(resp))
	w.(http.Flusher).Flush()
}
714698
func AuthTokenNonBlocking() (string, error) {
	cond.RLock()
	defer cond.RUnlock()
	if currentToken == "" {
		return "", ErrNotAuthenticated
	}

	if expired() {
		return "", ErrIdentityTokenExpired
	}

	return currentToken, nil
}
926504
func (fs *InterruptFS) EnableReadBlocking() {
	fs.mu.Lock()
	defer fs.mu.Unlock()

	fs.blockForReads = true
}
29401
func (f *LockPIDFile) Lock() (err error) {
	if isIOS {
		// on iOS, our share extension can have multiple copies running, and furthermore this lock
		// doesn't do anything there, so let's just do nothing.
		f.G().Log.Debug("Skipping PID file lock on iOS")
		return nil
	}

	if f.file, err = os.OpenFile(f.name, os.O_CREATE|os.O_RDWR, 0600); err != nil {
		return PIDFileLockError{f.name}
	}

	// LOCK_EX = exclusive
	// LOCK_NB = nonblocking
	if err = syscall.Flock(int(f.file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
		f.file.Close()
		f.file = nil
		return PIDFileLockError{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
}
321996
func (b *BaseKvdb) SetLockTimeout(timeout time.Duration) {
	b.lock.Lock()
	defer b.lock.Unlock()
	logrus.Infof("Setting lock timeout to: %v", timeout)
	b.LockTimeout = timeout
}
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
}
312356
func (sp *serverPeer) OnBlock(_ *peer.Peer, msg *wire.MsgBlock, buf []byte) {
	// Convert the raw MsgBlock to a btcutil.Block which provides some
	// convenience methods and things such as hash caching.
	block := btcutil.NewBlockFromBlockAndBytes(msg, buf)

	// Add the block to the known inventory for the peer.
	iv := wire.NewInvVect(wire.InvTypeBlock, block.Hash())
	sp.AddKnownInventory(iv)

	// Queue the block up to be handled by the block
	// manager and intentionally block further receives
	// until the bitcoin block is fully processed and known
	// good or bad.  This helps prevent a malicious peer
	// from queuing up a bunch of bad blocks before
	// disconnecting (or being disconnected) and wasting
	// memory.  Additionally, this behavior is depended on
	// by at least the block acceptance test tool as the
	// reference implementation processes blocks in the same
	// thread and therefore blocks further messages until
	// the bitcoin block has been fully processed.
	sp.server.syncManager.QueueBlock(block, sp.Peer, sp.blockProcessed)
	<-sp.blockProcessed
}
1082258
func (l *lockfile) Lock() {
	if l.ro {
		l.RLock()
	} else {
		l.lock(unix.F_WRLCK)
	}
}
386243
func (m *RWMutex) RUnlock() {
	m.mutex.RUnlock()
	atomic.AddInt64(&m.readers, -1)
}
571536
func (t *TxSerializer) lockLocked(ctx context.Context, key, table string) (bool, error) {
	q, ok := t.queues[key]
	if !ok {
		// First transaction in the queue i.e. we don't wait and return immediately.
		t.queues[key] = newQueueForFirstTransaction(t.concurrentTransactions)
		t.globalSize++
		return false, nil
	}

	if t.globalSize >= t.maxGlobalQueueSize {
		if t.dryRun {
			globalQueueExceededDryRun.Add(1)
			t.logGlobalQueueExceededDryRun.Warningf("Would have rejected BeginExecute RPC because there are too many queued transactions (%d >= %d)", t.globalSize, t.maxGlobalQueueSize)
		} else {
			globalQueueExceeded.Add(1)
			return false, vterrors.Errorf(vtrpcpb.Code_RESOURCE_EXHAUSTED,
				"hot row protection: too many queued transactions (%d >= %d)", t.globalSize, t.maxGlobalQueueSize)
		}
	}

	if q.size >= t.maxQueueSize {
		if t.dryRun {
			queueExceededDryRun.Add(table, 1)
			t.logQueueExceededDryRun.Warningf("Would have rejected BeginExecute RPC because there are too many queued transactions (%d >= %d) for the same row (table + WHERE clause: '%v')", q.size, t.maxQueueSize, key)
		} else {
			queueExceeded.Add(table, 1)
			return false, vterrors.Errorf(vtrpcpb.Code_RESOURCE_EXHAUSTED,
				"hot row protection: too many queued transactions (%d >= %d) for the same row (table + WHERE clause: '%v')", q.size, t.maxQueueSize, key)
		}
	}

	if q.availableSlots == nil {
		// Hot row detected: A second, concurrent transaction is seen for the
		// first time.

		// As an optimization, we deferred the creation of the channel until now.
		q.availableSlots = make(chan struct{}, t.concurrentTransactions)
		q.availableSlots <- struct{}{}

		// Include first transaction in the count at /debug/hotrows. (It was not
		// recorded on purpose because it did not wait.)
		t.Record(key)
	}

	t.globalSize++
	q.size++
	q.count++
	if q.size > q.max {
		q.max = q.size
	}
	// Publish the number of waits at /debug/hotrows.
	t.Record(key)

	if t.dryRun {
		waitsDryRun.Add(table, 1)
		t.logWaitsDryRun.Warningf("Would have queued BeginExecute RPC for row (range): '%v' because another transaction to the same range is already in progress.", key)
		return false, nil
	}

	// Unlock before the wait and relock before returning because our caller
	// Wait() holds the lock and assumes it still has it.
	t.mu.Unlock()
	defer t.mu.Lock()

	// Non-blocking write attempt to get a slot.
	select {
	case q.availableSlots <- struct{}{}:
		// Return waited=false because a slot was immediately available.
		return false, nil
	default:
	}

	// Blocking wait for the next available slot.
	waits.Add(table, 1)
	select {
	case q.availableSlots <- struct{}{}:
		return true, nil
	case <-ctx.Done():
		return true, ctx.Err()
	}
}
230154
func (w *Writer) writeBlock() {
	_, w.err = w.w.Write(w.buf[w.written:])
	w.i = 0
	w.j = headerSize
	w.written = 0
}
869215
func (m *Mutex) Lock(ctx context.Context) error {
	lockCtx, cancel := context.WithTimeout(ctx, m.timeout)
	defer cancel()
	return m.mutex.Lock(lockCtx)
}
875158
func (mutex *Mutex) TryLock() error {
	ret := int(C.SDL_TryLockMutex(mutex.cptr()))
	if ret != 0 {
		return GetError()
	}
	return nil
}
1230175
func (t *Transaction) LockTimeout(lockTimeout int) *Transaction {
	t.lockTimeout = &lockTimeout
	return t
}
1181010
func (jl *jsonLedger) readBlock(number uint64) (*cb.Block, bool) {
	name := jl.blockFilename(number)

	// In case of ongoing write, reading the block file may result in `unexpected EOF` error.
	// Therefore, we use file mutex here to prevent this race condition.
	fileLock.Lock()
	defer fileLock.Unlock()

	file, err := os.Open(name)
	if err == nil {
		defer file.Close()
		block := &cb.Block{}
		err = jsonpb.Unmarshal(file, block)
		if err != nil {
			return nil, true
		}
		logger.Debugf("Read block %d", block.Header.Number)
		return block, true
	}
	return nil, false
}
1320003
func (s *LocalState) writeLockInfo(info *LockInfo) error {
	path := s.lockInfoPath()
	info.Path = s.Path
	info.Created = time.Now().UTC()

	err := ioutil.WriteFile(path, info.Marshal(), 0600)
	if err != nil {
		return fmt.Errorf("could not write lock info for %q: %s", s.Path, err)
	}
	return nil
}