I am trying to append (write append) to a file from different threads (similar to logging) and so there is no inter-process locking needed.
I have studied flock in fcntl.h and it says flock can do granular lock along with inter-process which is not necessary in my situation.
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);
}
Will there be overhead as it can do granular locking and inter-process locking? What happens when program crashes when there is lock?
My current preference is mutex,
static std::mutex fileMutex;
fileMutex.lock();
//do my thing here
fileMutex.unlock();
Is it okay to go with the mutex approach as the synchronization (or locking) is needed only within the process(only multithreading),
or is it okay to implement the code with flock in fcntl.h?