文件加锁的目的是防止多个进程同时访问和修改同一文件导致数据损坏或不一致。1. c++本身没有跨平台文件加锁机制,但可通过操作系统api实现;2. 在posix系统中使用fcntl函数进行文件控制并加锁,通过f_wrlck设置独占锁、f_unlck解锁;3. 在windows系统中使用_lock_file函数结合_sopen以独占模式打开文件并通过_locking实现加锁与解锁;4. 避免死锁的方法包括统一锁获取顺序、引入超时机制、减少锁持有时间;5. 文件锁会影响性能,主要体现在锁的获取释放开销、进程间同步成本及并发性能受限;6. 选择锁类型需根据场景判断:共享锁用于多进程读操作,独占锁用于写操作确保排他性访问。

文件加锁是为了防止多个进程同时访问和修改同一个文件,造成数据损坏或不一致。C++本身没有直接提供跨平台的文件加锁机制,但我们可以借助操作系统提供的API来实现。主要有两种方式:fcntl(POSIX系统)和_lock_file(Windows系统)。

使用fcntl和_lock_file,可以在C++中构建一个跨平台的文件加锁机制,确保在不同操作系统上文件操作的安全性。

fcntl 实现(POSIX 系统)
立即学习“C++免费学习笔记(深入)”;
fcntl 是 POSIX 标准中定义的一个函数,用于文件控制。它提供了文件锁的功能,可以在 Linux、macOS 等 POSIX 兼容系统中使用。

#include <iostream>
#include <fstream>
#include <fcntl.h>
#include <unistd.h>
#include <cerrno>
class FileLock {
public:
FileLock(const std::string& filename) : filename_(filename), fd_(-1) {}
bool lock() {
fd_ = open(filename_.c_str(), O_RDWR);
if (fd_ == -1) {
std::cerr << "Failed to open file: " << filename_ << std::endl;
return false;
}
struct flock fl;
fl.l_type = F_WRLCK; // Write lock (exclusive lock)
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0; // Lock the entire file
if (fcntl(fd_, F_SETLK, &fl) == -1) { // F_SETLK: non-blocking lock request
if (errno == EACCES || errno == EAGAIN) {
std::cerr << "File is already locked by another process." << std::endl;
} else {
std::cerr << "Failed to lock file: " << filename_ << ", error: " << strerror(errno) << std::endl;
}
close(fd_);
fd_ = -1;
return false;
}
return true;
}
bool unlock() {
if (fd_ == -1) {
return true; // Not locked
}
struct flock fl;
fl.l_type = F_UNLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
if (fcntl(fd_, F_SETLK, &fl) == -1) {
std::cerr << "Failed to unlock file: " << filename_ << ", error: " << strerror(errno) << std::endl;
return false;
}
close(fd_);
fd_ = -1;
return true;
}
~FileLock() {
unlock();
}
private:
std::string filename_;
int fd_;
};
int main() {
FileLock lock("test.txt");
if (lock.lock()) {
std::cout << "File locked successfully." << std::endl;
// Perform file operations here
std::ofstream outfile("test.txt", std::ios::app);
outfile << "This is a test." << std::endl;
outfile.close();
std::cout << "Writing to file completed." << std::endl;
lock.unlock();
std::cout << "File unlocked." << std::endl;
} else {
std::cerr << "Failed to lock file." << std::endl;
}
return 0;
}这段代码首先尝试打开文件,然后使用 fcntl 函数尝试加锁。F_SETLK 表示非阻塞锁请求,如果文件已经被其他进程锁定,则立即返回错误。解锁时,将 fl.l_type 设置为 F_UNLCK。
_lock_file 实现(Windows 系统)
在 Windows 系统中,可以使用 _lock_file 函数来实现文件加锁。
#include <iostream>
#include <fstream>
#include <io.h>
#include <fcntl.h>
#include <share.h>
#include <windows.h>
class FileLock {
public:
FileLock(const std::string& filename) : filename_(filename), fd_(-1) {}
bool lock() {
// Open file in exclusive mode
fd_ = _sopen(filename_.c_str(), _O_RDWR, _SH_DENYNO, _S_IREAD | _S_IWRITE);
if (fd_ == -1) {
std::cerr << "Failed to open file: " << filename_ << std::endl;
return false;
}
// Lock the file
if (_locking(fd_, _LK_LOCK, 1024) == -1) {
std::cerr << "Failed to lock file: " << filename_ << std::endl;
_close(fd_);
fd_ = -1;
return false;
}
return true;
}
bool unlock() {
if (fd_ == -1) {
return true; // Not locked
}
if (_locking(fd_, _LK_UNLCK, 1024) == -1) {
std::cerr << "Failed to unlock file: " << filename_ << std::endl;
return false;
}
_close(fd_);
fd_ = -1;
return true;
}
~FileLock() {
unlock();
}
private:
std::string filename_;
int fd_;
};
int main() {
FileLock lock("test.txt");
if (lock.lock()) {
std::cout << "File locked successfully." << std::endl;
// Perform file operations here
std::ofstream outfile("test.txt", std::ios::app);
outfile << "This is a test." << std::endl;
outfile.close();
std::cout << "Writing to file completed." << std::endl;
lock.unlock();
std::cout << "File unlocked." << std::endl;
} else {
std::cerr << "Failed to lock file." << std::endl;
}
return 0;
}这段代码使用 _sopen 函数以独占模式打开文件,然后使用 _locking 函数尝试加锁和解锁。
如何避免死锁?
死锁通常发生在多个进程或线程互相等待对方释放资源时。避免死锁的一些策略包括:
- 锁的顺序: 确保所有进程以相同的顺序获取锁。
- 超时机制: 尝试获取锁时设置超时时间,如果超时则放弃并释放已持有的锁。
- 锁的粒度: 尽量减少锁的持有时间,避免长时间持有锁。
文件锁的性能影响有哪些?
文件锁会带来一定的性能开销,主要体现在以下几个方面:
- 锁的获取和释放: 每次加锁和解锁都需要进行系统调用,这会消耗一定的 CPU 时间。
- 进程间同步: 文件锁需要在多个进程之间进行同步,这会增加进程间通信的开销。
- 并发性能: 文件锁会限制并发访问,降低程序的整体性能。
如何选择合适的文件锁类型?
选择合适的文件锁类型取决于具体的应用场景。主要有两种类型的锁:
- 共享锁(Shared Lock): 允许多个进程同时读取文件,但不允许任何进程写入文件。
- 独占锁(Exclusive Lock): 只允许一个进程读取或写入文件,其他进程无法访问。
如果只需要读取文件,可以使用共享锁。如果需要写入文件,则必须使用独占锁。










