| 146 | static std::mutex cs_dir_locks; |
| 147 | |
| 148 | bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only) |
| 149 | { |
| 150 | std::lock_guard<std::mutex> ulock(cs_dir_locks); |
| 151 | fs::path pathLockFile = directory / lockfile_name; |
| 152 | |
| 153 | // If a lock for this directory already exists in the map, don't try to re-lock it |
| 154 | if (dir_locks.count(pathLockFile.string())) { |
| 155 | return true; |
| 156 | } |
| 157 | |
| 158 | // Create empty lock file if it doesn't exist. |
| 159 | FILE* file = fsbridge::fopen(pathLockFile, "a"); |
| 160 | if (file) fclose(file); |
| 161 | |
| 162 | try { |
| 163 | auto lock = MakeUnique<boost::interprocess::file_lock>(pathLockFile.string().c_str()); |
| 164 | if (!lock->try_lock()) { |
| 165 | return false; |
| 166 | } |
| 167 | if (!probe_only) { |
| 168 | // Lock successful and we're not just probing, put it into the map |
| 169 | dir_locks.emplace(pathLockFile.string(), std::move(lock)); |
| 170 | } |
| 171 | } catch (const boost::interprocess::interprocess_exception& e) { |
| 172 | return error("Error while attempting to lock directory %s: %s", directory.string(), e.what()); |
| 173 | } |
| 174 | return true; |
| 175 | } |
| 176 | |
| 177 | void ReleaseDirectoryLocks() |
| 178 | { |