- a writer < /strong>, который редко обновляет file;
- a reader , который часто читает файл.
Мой текущий подход заключается в следующем: < /p>
Код: Выделить всё
bool reader(const std::filesystem::path &f)
{
namespace fs = std::filesystem;
// Check for write lock.
auto write_lock_file = fs::path(f).replace_extension(".write.lock");
if (fs::exists(write_lock_file))
return false; // writer is active, aborting
// Create read lock.
auto read_lock_file = fs::path(f).replace_extension(".read.lock");
std::ofstream(read_lock_file).close();
// Recheck for write lock.
// When the writer creates the write lock, readers that check for the write
// lock will immediately abort, ensuring the writer can proceed as soon as
// it's ready.
if (fs::exists(write_lock_file))
{
fs::remove(read_lock_file); // cleanup
return false;
}
// READ WHAT NEEDED FROM f
fs::remove(read_lock_file);
return true;
}
< /code>
читатель и писатель используют отдельные файлы блокировки (.read.lockvoid writer(const std::filesystem::path &f)
{
namespace fs = std::filesystem;
// Create write lock.
auto write_lock_file = fs::path(f).replace_extension(".write.lock");
std::ofstream(write_lock_file).close();
// Wait for readers to finish.
// After creating the write lock, the writer waits for all readers to finish
// before proceeding. This ensures that existing readers are not interrupted,
// but no new readers can start.
auto read_lock_file = fs::path(f).replace_extension(".read.lock");
while (fs::exists(read_lock_file))
std::this_thread::sleep_for(100ms);
// WRITE NEW DATA INTO f
}
< /code>
Автор ждет, пока активные читатели закончат, прежде чем продолжить, но новые читатели заблокируются, как только писатель создает свой замок. < /p>
делает этот подход: < /p>
предотвратить условия гонки < /strong> между читателем и писателем? < /li>
Избегайте тупиков < / Strong> или длительная блокировка?>
Подробнее здесь: https://stackoverflow.com/questions/793 ... -processes
Мобильная версия