diff --git a/tdutils/td/utils/port/FileFd.cpp b/tdutils/td/utils/port/FileFd.cpp index 912885759..5861136b4 100644 --- a/tdutils/td/utils/port/FileFd.cpp +++ b/tdutils/td/utils/port/FileFd.cpp @@ -286,11 +286,32 @@ Result FileFd::pread(MutableSlice slice, int64 offset) const { static std::mutex in_process_lock_mutex; static std::unordered_set 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 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 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 {