FileFd: create_local_lock function

GitOrigin-RevId: 8d782e0194f4e2e7b0d9ceef9dad4a1051ed393b
This commit is contained in:
Arseny Smirnov 2018-10-30 11:35:50 +03:00
parent 4e03ee1293
commit 0aa06cbea5
1 changed files with 24 additions and 20 deletions

View File

@ -286,11 +286,32 @@ Result<size_t> FileFd::pread(MutableSlice slice, int64 offset) const {
static std::mutex in_process_lock_mutex;
static std::unordered_set<string> locked_files;
Status FileFd::lock(const LockFlags flags, const string &path, int32 max_tries) {
static Status create_local_lock(const string &path, int32 max_tries) {
if (max_tries <= 0) {
return Status::Error(0, "Can't lock file: wrong max_tries");
}
while (true) {
{ // mutex lock scope
std::lock_guard<std::mutex> lock(in_process_lock_mutex);
if (locked_files.find(path) == locked_files.end()) {
VLOG(fd) << "Lock file \"" << path << '"';
locked_files.insert(path);
return Status::OK();
}
}
if (--max_tries <= 0) {
break;
}
usleep_for(100000);
}
return Status::Error(
0, PSLICE() << "Can't lock file \"" << path << "\", because it is already in use by current program");
}
Status FileFd::lock(const LockFlags flags, const string &path, int32 max_tries) {
bool need_local_unlock = false;
if (!path.empty()) {
if (flags == LockFlags::Unlock) {
@ -300,25 +321,8 @@ Status FileFd::lock(const LockFlags flags, const string &path, int32 max_tries)
} else {
CHECK(flags == LockFlags::Write);
VLOG(fd) << "Trying to lock file \"" << path << '"';
while (true) {
{ // mutex lock scope
std::lock_guard<std::mutex> lock(in_process_lock_mutex);
if (locked_files.find(path) == locked_files.end()) {
VLOG(fd) << "Lock file \"" << path << '"';
need_local_unlock = true;
locked_files.insert(path);
break;
}
}
if (--max_tries > 0) {
usleep_for(100000);
continue;
}
return Status::Error(
0, PSLICE() << "Can't lock file \"" << path << "\", because it is already in use by current program");
}
TRY_STATUS(create_local_lock(path, max_tries));
need_local_unlock = true;
}
}
SCOPE_EXIT {