Acquire a lock.
        This method blocks until the lock is unlocked, then sets it to
        locked and returns True.
544041
def acquire(self):
        
        if not self._locked and all(w.cancelled() for w in self._waiters):
            self._locked = True
            return True

        fut = self._loop.create_future()

        self._waiters.append(fut)
        try:
            yield from fut
            self._locked = True
            return True
        except asyncio.CancelledError:
            if not self._locked:  # pragma: no cover
                self._wake_up_first()
            raise
        finally:
            self._waiters.remove(fut)
1320213
def datalock(self, acquire=True):
        # type: (_BaseResumeManager) -> None
        
        if acquire:
            self._lock.acquire()
        try:
            yield
        finally:
            if acquire:
                self._lock.release()
255559
def with_lock(lock, func, *args, **kwargs):
    
    d = lock.acquire()

    def release_lock(result):
        deferred = lock.release()
        return deferred.addCallback(lambda x: result)

    def lock_acquired(lock):
        return defer.maybeDeferred(func, *args, **kwargs).addBoth(release_lock)

    d.addCallback(lock_acquired)
    return d
315707
def _AcquireLock(self,
                   urn,
                   blocking=None,
                   blocking_lock_timeout=None,
                   lease_time=None,
                   blocking_sleep_interval=None):
    """"""
    if urn is None:
      raise ValueError("URN cannot be None")

    urn = rdfvalue.RDFURN(urn)

    try:
      return data_store.DB.LockRetryWrapper(
          urn,
          retrywrap_timeout=blocking_sleep_interval,
          retrywrap_max_timeout=blocking_lock_timeout,
          blocking=blocking,
          lease_time=lease_time)
    except data_store.DBSubjectLockError as e:
      raise LockError(e)
978043
private Boolean acquireLock(final BooleanMutex mutex) {
        try {
            do {
                if (id == null) {// 构建当前lock的唯一标识
                    long sessionId = getSessionId();
                    String prefix = "x-" + sessionId + "-";
                    // 如果第一次，则创建一个节点
                    String path = zookeeper.create(root + "/" + prefix, data, CreateMode.EPHEMERAL_SEQUENTIAL);
                    int index = path.lastIndexOf("/");
                    id = StringUtils.substring(path, index + 1);
                    idName = new LockNode(id);
                }

                if (id != null) {
                    List<String> names = zookeeper.getChildren(root);
                    if (names.isEmpty()) {
                        logger.warn("lock lost with scene:empty list, id[] and node[]", id, idName);
                        unlock();// 异常情况，退出后重新创建一个
                    } else {
                        // 对节点进行排序
                        SortedSet<LockNode> sortedNames = new TreeSet<LockNode>();
                        for (String name : names) {
                            sortedNames.add(new LockNode(name));
                        }

                        if (sortedNames.contains(idName) == false) {
                            logger.warn("lock lost with scene:not contains ,id[] and node[]", id, idName);
                            unlock();// 异常情况，退出后重新创建一个
                            continue;
                        }

                        // 将第一个节点做为ownerId
                        ownerId = sortedNames.first().getName();
                        if (mutex != null && isOwner()) {
                            mutex.set(true);// 直接更新状态，返回
                            return true;
                        } else if (mutex == null) {
                            return isOwner();
                        }

                        SortedSet<LockNode> lessThanMe = sortedNames.headSet(idName);
                        if (!lessThanMe.isEmpty()) {
                            // 关注一下排队在自己之前的最近的一个节点
                            LockNode lastChildName = lessThanMe.last();
                            lastChildId = lastChildName.getName();
                            // 异步watcher处理
                            IZkConnection connection = zookeeper.getConnection();
                            // zkclient包装的是一个持久化的zk，分布式lock只需要一次性的watcher，需要调用原始的zk链接进行操作
                            ZooKeeper orginZk = ((ZooKeeperx) connection).getZookeeper();
                            Stat stat = orginZk.exists(root + "/" + lastChildId, new AsyncWatcher() {

                                public void asyncProcess(WatchedEvent event) {
                                    if (!mutex.state()) { // 避免重复获取lock
                                        acquireLock(mutex);
                                    } else {
                                        logger.warn("locked successful.");
                                    }
                                }

                            });

                            if (stat == null) {
                                acquireLock(mutex);// 如果节点不存在，需要自己重新触发一下，watcher不会被挂上去
                            }
                        } else {
                            if (isOwner()) {
                                mutex.set(true);
                            } else {
                                logger.warn("lock lost with scene:no less ,id[] and node[]", id, idName);
                                unlock();// 可能自己的节点已超时挂了，所以id和ownerId不相同
                            }
                        }
                    }
                }
            } while (id == null);
        } catch (KeeperException e) {
            exception = e;
            if (mutex != null) {
                mutex.set(true);
            }
        } catch (InterruptedException e) {
            interrupt = e;
            if (mutex != null) {
                mutex.set(true);
            }
        } catch (Throwable e) {
            other = e;
            if (mutex != null) {
                mutex.set(true);
            }
        }

        if (isOwner() && mutex != null) {
            mutex.set(true);
        }
        return Boolean.FALSE;
    }
327633
@Override
  public void lock() throws JobLockException {
    try {
      this.lock.acquire();
    } catch (Exception e) {
      throw new JobLockException("Failed to acquire lock " + this.lockPath, e);
    }
  }
1334305
public void ratifyLockAction (ClientObject caller, NodeObject.Lock lock, boolean acquire)
    {
        LockHandler handler = _locks.get(lock);
        if (handler != null && Objects.equal(handler.getNodeName(), _nodeName)) {
            handler.ratify(caller, acquire);
        } else {
            // this is not an error condition, as we may have cancelled the handler or
            // allowed another to take priority
        }
    }
628110
def lock(self):
        
        if self.cache.get(self.lock_name):
            return False
        else:
            self.cache.set(self.lock_name, timezone.now(), self.timeout)
            return True
880581
public boolean acquireGlobalLock(boolean exclusive, long timeout) {
      log.tracef("About to acquire global lock. Exclusive? %s", exclusive);
      boolean success = true;
      for (int i = 0; i < sharedLocks.length; i++) {
         Lock toAcquire = exclusive ? sharedLocks[i].writeLock() : sharedLocks[i].readLock();
         try {
            success = toAcquire.tryLock(timeout, TimeUnit.MILLISECONDS);
            if (!success) {
               if (trace) log.tracef("Could not acquire lock on %s. Exclusive? %b", toAcquire, exclusive);
               break;
            }
         } catch (InterruptedException e) {
            if (trace) log.trace("Caught InterruptedException while trying to acquire global lock", e);
            success = false;
            Thread.currentThread().interrupt();
         } finally {
            if (!success) {
               for (int j = 0; j < i; j++) {
                  Lock toRelease = exclusive ? sharedLocks[j].writeLock() : sharedLocks[j].readLock();
                  toRelease.unlock();
               }
            }
         }
      }
      return success;
   }
913055
def acquire_restore(lock, state):
    """"""
    if hasattr(lock, '_acquire_restore'):
        lock._acquire_restore(state)
    elif hasattr(lock, 'acquire'):
        lock.acquire()
    else:
        raise TypeError('expecting Lock/RLock')
275190
@Override
  public void acquire(HLock lock) {
    acquire(lock, Long.MAX_VALUE - System.currentTimeMillis() - 10000);
  }
109698
public synchronized void unlock()
  {
    if (tc.isEntryEnabled())
      SibTr.entry(tc, "unlock", this);

    // If the subscription locks are down to zero then notify the threads waiting
    // for the subscriptionTable lock.
    synchronized (iMutex)
    {
      // If we are exclusively locked, then just return, as long as
      // the thread that is calling is the thread that holds the
      // exclusive lock.
      if (iExclusivelyLocked && iExclusiveLockHolder == Thread.currentThread())
      {
        if (tc.isEntryEnabled())
          SibTr.exit(tc, "unlock");
        return;
      }

      // Decrement the lock count and notify the other threads if no 
      // one holds the lock any more.
      if (--iLockCount == 0)
        notifyAll();
        
      if (iLockCount < 0)
      {      
        if (tc.isEntryEnabled()) 
          SibTr.exit(tc, "unlock", "SIErrorException");
        
        SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0001",
          new Object[] {
            "com.ibm.ws.sib.processor.utils.LockManager",
            "1:196:1.19" });
          
        throw new SIErrorException(
          nls.getFormattedMessage(
            "INTERNAL_MESSAGING_ERROR_CWSIP0001",
            new Object[] {
              "com.ibm.ws.sib.processor.utils.LockManager",
              "1:203:1.19" },
            null));
      }        
    }

    if (tc.isEntryEnabled())
      SibTr.exit(tc, "unlock");
  }
356445
def acquire_lock(lock_name)
      begin
        acquired = false
        sql = lock_query(lock_name)
        connection.query(sql) do |result|
          acquired = result.fetch_row.first == "1"
        end
        acquired
      rescue ::Exception
        false
      end
    end
204171
public final Lock lock(Object key) {
        Lock lock = this.locks.get(key);
        lock.lock();
        return lock;
    }
831742
public boolean acquire(final Lock lock) {
        lock.setUniqueId(this.uniqueId);
        if (this.lockTimeout > 0) {
            lock.setExpirationDate(ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(this.lockTimeout));
        } else {
            lock.setExpirationDate(null);
        }
        var success = false;
        try {
            if (lock.getApplicationId() != null) {
                this.entityManager.merge(lock);
            } else {
                lock.setApplicationId(this.applicationId);
                this.entityManager.persist(lock);
            }
            success = true;
        } catch (final Exception e) {
            success = false;
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[{}] could not obtain [{}] lock.", this.uniqueId, this.applicationId, e);
            } else {
                LOGGER.info("[{}] could not obtain [{}] lock.", this.uniqueId, this.applicationId);
            }
        }
        return success;
    }
303288
def acquire_lock(cls, mode, user=None):
        
        if not user:
            return

        with EteSyncCache.lock:
            cls.user = user

            cls.etesync = cls._get_etesync_for_user(cls.user)

            if cls._should_sync():
                cls._mark_sync()
                cls.etesync.get_or_create_user_info(force_fetch=True)
                cls.etesync.sync_journal_list()
                for journal in cls.etesync.list():
                    cls.etesync.pull_journal(journal.uid)
            yield
            if cls.etesync.journal_list_is_dirty():
                cls.etesync.sync_journal_list()
            for journal in cls.etesync.list():
                if cls.etesync.journal_is_dirty(journal.uid):
                    cls.etesync.sync_journal(journal.uid)

            cls.etesync = None
            cls.user = None
371077
def __checkLock(self):
        
        if self._isLocked:
            if (time.time() - self._timer) > TIMEOUT_TIMES[self._operation]:
                self.__unLock()
                return False
            return True
        return False