我想從不同的線程(類似於日誌記錄)追加(寫入附加)到一個文件,因此不需要進程間鎖定。C++ -mutex或flock fcntl.h只鎖定寫操作
我已經在fcntl.h中研究了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模式下打開! –