【发布时间】:2017-07-01 10:18:18
【问题描述】:
我正在尝试从不同的线程(类似于日志记录)将文件附加(写入附加),因此不需要进程间锁定。
我在 fcntl.h 中研究了flock,它说flock 可以与进程间一起进行粒度锁定,这在我的情况下是不必要的。
char* file = "newfile.txt";
int fd;
struct flock lock;
printf("opening %s\n", file);
fd = open(file, O_APPEND);
if (fd >= 0) {
memset(&lock, 0, sizeof (lock));
lock.l_type = F_WRLCK;
fcntl(fd, F_SETLKW, &lock);
//do my thing here
lock.l_type = F_UNLCK;
fcntl(fd, F_SETLKW, &lock);
close(fd);
}
会不会有开销,因为它可以进行粒度锁定和进程间锁定?有锁时程序崩溃怎么办?
我目前的偏好是互斥体,
static std::mutex fileMutex;
fileMutex.lock();
//do my thing here
fileMutex.unlock();
是否可以使用互斥锁方法,因为仅在进程内需要同步(或锁定)(仅多线程),
或者用fcntl.h中的flock实现代码可以吗?
【问题讨论】:
-
以 O_APPEND 模式打开!
标签: c++ linux file mutex filelock