I have two threads, one reads a file and one writes to the same file.
I want to lock the file while writing so read is blocked until the file is unlocked.
I tried using flockfile amd funlockfile without success.
Can someone please show the correct way to achieve this.
thread 1:
1 2 3 4 5 6 7 8 9 10 11
FILE * F;
string outFile = "myfile";
string out2File = "string to be stored";
F = fopen(outFile.c_str(), "a");
flockfile(F);
fputs(out2File.c_str(), F);
funlockfile(F);
fclose(FileStream);
In my experience, fopen fails if the file has been opened with write permissions (presumably for this very reason). Although in append mode it might be different (I never use append).
Anyway -- "blocking" and "mutually exclusive access to a file" sounds an awful lot like you want a Mutex. Make a mutex and lock it during critical sections (file accesses). Mutexes are fundamental for multithreading and any threading lib should have them.