Start to acquire lock in another routine. Call trylock or lock later to acquire the lock. Call unlock to cancel the lock routine
495055
def beginlock(self, container):
        ""
        if self.locked:
            return True
        if self.lockroutine:
            return False
        self.lockroutine = container.subroutine(self._lockroutine(container), False)
        return self.locked
559939
def handle_lock(handle):
    
    
    def wrapper(self, *args, **options):
        def on_interrupt(signum, frame):
            # It's necessary to release lockfile
            sys.exit()
        signal.signal(signal.SIGTERM, on_interrupt)

        start_time = time.time()
        try:
            verbosity = int(options.get('verbosity', 0))
        except ValueError:
            verbosity = 0
        logger = logging.getLogger(self.__module__)
        if verbosity == 0:
            logger.level = logging.WARNING
        elif verbosity == 1:
            logger.level = logging.INFO
        else:
            logger.level = logging.DEBUG
       
        logger.debug("-" * 72)
        
        lock_name = self.__module__.split('.').pop()
        lock = FileLock(os.path.join(LOCK_ROOT, lock_name))
        
        logger.debug("%s - acquiring lock..." % lock_name)
        try:
            lock.acquire(LOCK_WAIT_TIMEOUT)
        except AlreadyLocked:
            logger.debug("lock already in place. quitting.")
            return
        except LockTimeout:
            logger.debug("waiting for the lock timed out. quitting.")
            return
        logger.debug("acquired.")
        
        try:
            handle(self, logger, *args, **options)
        except (KeyboardInterrupt, SystemExit):
            pass
        except:
            import traceback
            logging.warn("Command Failed")
            logging.warn('=' * 72)
            logging.warn(traceback.format_exc())
            logging.warn('=' * 72)
        
        logger.debug("releasing lock...")
        lock.release()
        logger.debug("released.")
        
        logger.info("done in %.2f seconds" % (time.time() - start_time))
        return
        
    return wrapper
1027682
def thread_lock(lock):
    """"""
    if hasattr(lock, '_lock'):
        return lock._lock
    elif hasattr(lock, 'acquire'):
        return lock
    else:
        raise TypeError('expecting Lock/RLock')
87761
public void lock() {
		if (cancel != null)
			return;
		if (error != null)
			return;
		Thread t;
		BlockedThreadHandler blockedHandler;
		do {
			synchronized (this) {
				if (!locked) {
					locked = true;
					return;
				}
				t = Thread.currentThread();
				blockedHandler = Threading.getBlockedThreadHandler(t);
				if (blockedHandler != null) break;
				try { this.wait(0); }
				catch (InterruptedException e) { continue; }
			}
		} while (true);
		blockedHandler.blocked(this, 0);
	}
1177261
def acquire_try_once(self):
        
        
        if self.is_locked_by_me():
            return True
        else:
            try:
                self.fd = os.open(self.lock_filename, os.O_CREAT | os.O_RDWR | os.O_EXCL)
            except FileExistsError:
                logger.debug('I tried to get the lock {}, but another process was faster.'.format(self.lock_filename))
                return False
            else:
                os.write(self.fd, str(self.pid).encode('utf-8'))
                logger.debug('I got the lock {}.'.format(self.lock_filename))
                return True
375405
void unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK lock) {
        synchronized (reqQueueLockObject) {
            for (ServerRequest req : queue) {
                if (req != null) {
                    req.removeProcessWaitLock(lock);
                }
            }
        }
    }
232417
void tryLock() {
		try {
			if (!delegate.tryLock(lockTimeout, lockTimeoutUnit)) {
				throw new KeyLockManagerTimeoutException(lockTimeout, lockTimeoutUnit);
			}
		} catch (final InterruptedException e) {
			throw new KeyLockManagerInterruptedException();
		}
	}
591318
def acquire(self, blocking=True, timeout=-1):
        """"""
        if not isinstance(timeout, (int, float)):
            raise TypeError('a float is required')

        if blocking:
            # blocking indefinite
            if timeout == -1:
                with self.__condition:
                    while not self.__lock.acquire(False):
                        # condition with timeout is interruptable
                        self.__condition.wait(60)
                return True

            # same as non-blocking
            elif timeout == 0:
                return self.__lock.acquire(False)

            elif timeout < 0:
                raise ValueError('timeout value must be strictly positive (or -1)')

            # blocking finite
            else:
                start = time()
                waited_time = 0
                with self.__condition:
                    while waited_time < timeout:
                        if self.__lock.acquire(False):
                            return True
                        else:
                            self.__condition.wait(timeout - waited_time)
                            waited_time = time() - start
                return False

        elif timeout != -1:
            raise ValueError('can\'t specify a timeout for a non-blocking call')

        else:
            # non-blocking
            return self.__lock.acquire(False)
782180
public synchronized Lease acquire(@Nonnull FilePath p, boolean quick, Object context) throws InterruptedException {
        Entry e;

        Thread t = Thread.currentThread();
        String oldName = t.getName();
        t.setName("Waiting to acquire "+p+" : "+t.getName());
        try {
            while (true) {
                e = inUse.get(p.getRemote());
                if (e==null || e.context==context)
                    break;
                wait();
            }
        } finally {
            t.setName(oldName);
        }
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "acquired " + p + (e == null ? "" : " with lock count " + e.lockCount), new Throwable("from " + this));
        }
        
        if (e!=null)    e.lockCount++;
        else            inUse.put(p.getRemote(), new Entry(p,quick,context));
        return lease(p);
    }
562916
def start(self):
        
        # Delete any expired locks first
        self.delete_expired_locks()
        try:
            with transaction.atomic():
                self.lock = DBMutex.objects.create(lock_id=self.lock_id)
        except IntegrityError:
            raise DBMutexError('Could not acquire lock: {0}'.format(self.lock_id))
742931
def simple_locking(lock_id, expiration=None):
    
    def inner_decorator(function):
        def wrapper(*args, **kwargs):
            try:
                # Trying to acquire lock
                lock = Lock.acquire_lock(lock_id, expiration)
            except LockError:
                # Unable to acquire lock - non fatal
                pass
            else:
                # Lock acquired, proceed normally, release lock afterwards
                logger.debug('acquired lock: %s' % lock_id)
                try:
                    return function(*args, **kwargs)
                except:
                    # Re raise any exception that occured when calling wrapped
                    # function
                    raise
                finally:
                    lock.release()
        return wraps(function)(wrapper)
    return inner_decorator
315985
def release_lock():
    """"""
    get_lock.n_lock -= 1
    assert get_lock.n_lock >= 0
    # Only really release lock once all lock requests have ended.
    if get_lock.lock_is_enabled and get_lock.n_lock == 0:
        get_lock.start_time = None
        get_lock.unlocker.unlock()
1166469
def lock!(*args)
      fail 'No block passed' unless block_given?

      lock(*args) do |lock_info|
        raise LockError, 'failed to acquire lock' unless lock_info
        return yield
      end
    end
595077
async def release(self):
        ""
        expected_token = self.local.token
        if expected_token is None:
            raise LockError("Cannot release an unlocked lock")
        self.local.token = None
        await self.do_release(expected_token)
471868
def acquire(self, signal=True):
        
        if not self.needs_lock:
            return
        with self.synclock:
            while not self.lock.acquire(False):
                self.synclock.wait()
            if signal:
                self.acquired_event(self)
            self.synclock.notify_all()
847214
def _acquire_lock_and_exit(lock_manager: ConsulLockManager, configuration: CliLockConfiguration):
    
    lock = _acquire_lock(lock_manager, configuration)
    print(json.dumps(lock, cls=ConsulLockInformationJSONEncoder, sort_keys=True))

    if lock is None:
        logger.error(f"Unable to acquire lock: {configuration.key}")
        exit(UNABLE_TO_ACQUIRE_LOCK_EXIT_CODE)

    exit(SUCCESS_EXIT_CODE)
1178496
public void meetWith(LockSet other) {
        for (int i = 0; i + 1 < array.length; i += 2) {
            int valueNumber = array[i];
            if (valueNumber < 0) {
                break;
            }

            int mine = array[i + 1];
            int his = other.getLockCount(valueNumber);
            array[i + 1] = mergeValues(mine, his);
        }

        for (int i = 0; i + 1 < other.array.length; i += 2) {
            int valueNumber = other.array[i];
            if (valueNumber < 0) {
                break;
            }

            int mine = getLockCount(valueNumber);
            int his = other.array[i + 1];
            setLockCount(valueNumber, mergeValues(mine, his));
        }

        setDefaultLockCount(0);
    }