0

I'm trying to figure out what happens if I write to the same file using the method [NSData writeToFile:atomically:YES] from multiple threads. Is there a guarantee that the file will be uncorrupted after the threads finish writing to it?

For simplicity you can assume the file system is APFS (iOS 11+).

The question is also relevant for NSFileManager's [replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error:]

byohay
  • 272
  • 4
  • 11
  • 1
    Why would you write to a file using multiple threads anyway? – trojanfoe Sep 19 '19 at 07:45
  • It is thread-safe, but you'll get only the contents of the last write. I don't see any practical use case where you would be concerned by thread safety in this case. – Vlad Rusu Sep 19 '19 at 08:10
  • A possible scenario can be a network library that was requested to download the same file from two threads, and each thread copies the file to the same directory when it finishes. Of course, it is redundant to invoke the same request multiple times, but I don't want to assume that it won't happen. – byohay Sep 19 '19 at 08:43
  • 1
    If it's possible the multiple threads can write to the same file then you should provide functionality to manage it. This would allow you to deny the action, for example, rather than trampling over another thread's data. – trojanfoe Sep 19 '19 at 09:55
  • Thanks! Eventually I decided to go with your advice and manage it. – byohay Sep 22 '19 at 07:09

0 Answers0