This is a context manager to acquire a lock on the Lock file that will be used to
        prevent synchronous cache operations between workers.
        :yields: File descriptor for cache lock file in w mode
962683
def cacheLock(self):
        
        cacheLockFile = open(self.cacheLockFile, 'w')
        try:
            flock(cacheLockFile, LOCK_EX)
            logger.debug("CACHE: Obtained lock on file %s" % self.cacheLockFile)
            yield cacheLockFile
        except IOError:
            logger.critical('CACHE: Unable to acquire lock on %s' % self.cacheLockFile)
            raise
        finally:
            cacheLockFile.close()
            logger.debug("CACHE: Released lock")
1209684
def write_file_list_cache(opts, data, list_cache, w_lock):
    '''
    
    '''
    serial = salt.payload.Serial(opts)
    with salt.utils.files.fopen(list_cache, 'w+b') as fp_:
        fp_.write(serial.dumps(data))
        _unlock_cache(w_lock)
        log.trace('Lockfile %s removed', w_lock)
126620
def lock(self, block=True):
		
		self._locked = True
		return self._lock.acquire(block)
1022320
def get(**file_finder_args)
      @cache[file_finder_args] || @mutex.synchronize do
        @cache[file_finder_args] ||= begin
          args = file_finder_args.dup
          args[:exclude] = @defaults[:exclude] + (args[:exclude] || [])
          args[:exclude].uniq!
          CachingFileFinder.new(**args)
        end
      end
    end
249812
def _obtain_lock_or_raise(self):
        """"""
        if self._has_lock():
            return
        lock_file = self._lock_file_path()
        if os.path.isfile(lock_file):
            raise IOError("Lock for file %r did already exist, delete %r in case the lock is illegal" % (self._file_path, lock_file))

        try:
            fd = os.open(lock_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0)
            os.close(fd)
        except OSError,e:
            raise IOError(str(e))

        self._owns_lock = True
167395
def with_lock
      @zk_lock ||= @zk.locker(current_lock_path)

      begin
        @zk_lock.lock!(true)
      rescue Exception
        # handle shutdown case
        running? ? raise : return
      end

      if running?
        @zk_lock.assert!
        yield
      end
    ensure
      if @zk_lock
        begin
          @zk_lock.unlock!
        rescue => ex
          logger.warn("Failed to release lock: #{ex.inspect}")
        end
      end
    end
965484
def iter_sync(fileobj, max_read):
    

    read = 0
    size = 2
    last_byte = b""
    is_second = lambda b: ord(b) & 0xe0 == 0xe0

    while read < max_read:
        data_offset = fileobj.tell()
        new_data = fileobj.read(min(max_read - read, size))
        if not new_data:
            return
        read += len(new_data)

        if last_byte == b"\xff" and is_second(new_data[0:1]):
            fileobj.seek(data_offset - 1, 0)
            yield

        size *= 2
        last_byte = new_data[-1:]

        find_offset = 0
        while True:
            index = new_data.find(b"\xff", find_offset)
            # if not found or the last byte -> read more
            if index == -1 or index == len(new_data) - 1:
                break

            if is_second(new_data[index + 1:index + 2]):
                fileobj.seek(data_offset + index, 0)
                yield
            find_offset = index + 1

        fileobj.seek(data_offset + len(new_data), 0)
685926
def wait_lock(lk_fn, dest, wait_timeout=0):
    '''
    
    '''
    if not os.path.exists(lk_fn):
        return False
    if not os.path.exists(dest):
        # The dest is not here, sleep for a bit, if the dest is not here yet
        # kill the lockfile and start the write
        time.sleep(1)
        if not os.path.isfile(dest):
            _unlock_cache(lk_fn)
            return False
    timeout = None
    if wait_timeout:
        timeout = time.time() + wait_timeout
    # There is a lock file, the dest is there, stat the dest, sleep and check
    # that the dest is being written, if it is not being written kill the lock
    # file and continue. Also check if the lock file is gone.
    s_count = 0
    s_size = os.stat(dest).st_size
    while True:
        time.sleep(1)
        if not os.path.exists(lk_fn):
            return False
        size = os.stat(dest).st_size
        if size == s_size:
            s_count += 1
            if s_count >= 3:
                # The file is not being written to, kill the lock and proceed
                _unlock_cache(lk_fn)
                return False
        else:
            s_size = size
        if timeout:
            if time.time() > timeout:
                raise ValueError(
                    'Timeout({0}s) for {1} (lock: {2}) elapsed'.format(
                        wait_timeout, dest, lk_fn
                    )
                )
    return False
311676
def _lock(self, url: str, name: str, hash_: str):
        
        self._new_lock.append({
            'url': url,
            'name': name,
            'hash': hash_,
        })
        self._stale_files.pop(name, None)
632306
def get_lockfile_filename(impl, working_dir):
    
    lockfile_name = impl.get_virtual_chain_name() + ".lock"
    return os.path.join(working_dir, lockfile_name)
107778
File getCacheFile(TemplateClass tc) {
        String id = cacheFileName(tc, ".rythm");
        return getCacheFile(id);
    }
1164933
def get(self, path):
        
        assert isinstance(path, mitogen.core.UnicodeType)
        self._lock.acquire()
        try:
            if path in self._cache:
                return self._cache[path]
            latch = mitogen.core.Latch()
            waiters = self._waiters.setdefault(path, [])
            waiters.append(lambda: latch.put(None))
        finally:
            self._lock.release()

        LOG.debug('%r.get(%r) waiting for uncached file to arrive', self, path)
        latch.get()
        LOG.debug('%r.get(%r) -> %r', self, path, self._cache[path])
        return self._cache[path]
328158
private File getWriteLock() {
        File[] lckFiles = this.lockPath.listFiles(lockFilter);
        for (final File lckFile : lckFiles) {
            if (lockFilter.isWriterLockFile(lckFile)) {
                return lckFile;
            }
        }

        return null;
    }
344831
private Path getFileForLockFile(Path lockFile, Path sourceDirPath)
          throws IOException {
    String lockFileName = lockFile.getName();
    Path dataFile = new Path(sourceDirPath + Path.SEPARATOR + lockFileName + inprogress_suffix);
    if( hdfs.exists(dataFile) ) {
      return dataFile;
    }
    dataFile = new Path(sourceDirPath + Path.SEPARATOR +  lockFileName);
    if(hdfs.exists(dataFile)) {
      return dataFile;
    }
    return null;
  }
654747
def CacheFileObject(self, path_spec, file_object):
    
    self._file_object_cache.CacheObject(path_spec.comparable, file_object)
1084626
def _exclusive_lock(path):
    """"""
    _create_file_dirs(path)
    fd = os.open(path, os.O_WRONLY | os.O_CREAT, 0o600)

    try:
        retries_left = _LOCK_RETRIES
        success = False

        while retries_left > 0:
            # try to acquire the lock in a loop
            # because gevent doesn't treat flock as IO,
            # so waiting here without yielding would get the worker killed
            try:
                fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
                success = True
                break
            except IOError as e:
                if e.errno in [errno.EAGAIN, errno.EWOULDBLOCK]:
                    # This yields execution to other green threads.
                    gevent.sleep(_LOCK_SLEEP_TIME_S)
                    retries_left -= 1
                else:
                    raise

        if success:
            yield
        else:
            raise ConcurrentModificationError(path)
    finally:
        if success:
            fcntl.flock(fd, fcntl.LOCK_UN)
        os.close(fd)
245010
public synchronized boolean lock() throws KeeperException, InterruptedException {
        if (isClosed()) {
            return false;
        }
        ensurePathExists(dir);

        return (Boolean) retryOperation(zop);
    }