Reputation: 71048
If I have two threads in my Cocoa app, and (let's say), I'm reading from file X on the disk with an NSData +dataWithContentsOfFile:
, and another thread is concurrently updating or replacing that same file X, with, say a -writeToPath:atomically:
?
I'm unfamiliar with what Cocoa's standard file read/writes modes are. Could the read operation see corruption mid-file? If so, what is the standard way around this? Use POSIX functions to allow effectively multiple-readers but only one exclusive writer?
Thanks for insight that bridges my understanding between the Cocoa API and the underlying filesystem.
Upvotes: 0
Views: 207
Reputation: 96363
Could the read operation see corruption mid-file?
Not if you set atomically
to YES
. What that does is writes the data to a temporary file, then overwrites the intended destination with the temporary file. This is atomic (on local file-systems, anyway) because it's just a quick edit to the directory.
The read might only get part of the data if you were to start writing to the intended destination immediately and weren't finished yet—i.e., you passed atomically:NO
. So, in cases like this, don't do that—pass YES
.
Upvotes: 1