Skip to content

Instantly share code, notes, and snippets.

@jonnyyu
Created October 11, 2022 03:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonnyyu/0b075aaf949555c5291248f53db1b3d2 to your computer and use it in GitHub Desktop.
Save jonnyyu/0b075aaf949555c5291248f53db1b3d2 to your computer and use it in GitHub Desktop.
file-based named mutex like lock for multi-processes.
#pragma once
#include <filesystem>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
using std::ofstream;
using std::filesystem::path;
using boost::interprocess::file_lock;
using boost::interprocess::scoped_lock;
namespace utils
{
class FileLock
{
path _path;
ofstream _file;
file_lock _lock;
scoped_lock<file_lock> _scope;
public:
FileLock(const path& filePath)
: _path(filePath),
_file(_path, std::ios_base::app),
_lock(_path.string().c_str()),
_scope(_lock)
{
log("[DEBUG]: Creating file lock {}\n", _path);
}
~FileLock()
{
log("[DEBUG]: Releasing file lock {}\n", _path);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment