0

I'd like write a file to disk using multiple NSOutputStreams (each one in a different thread). I know how to handle the threading issue, but I can't figure out what to use to write different byte-ranges to a single file at the same time.

For example, say the target file will be 100 MB on disk when the write process is complete. I have 4 threads with 4 streams (we'll call them s0, s1, s2, and s3) that want to write 25MB to the target file. I want each stream (s0-3) to be able to write at the same time to their respective target byte ranges (e.g. s0 writes from 0MB-25MB, s1 from 25MB-50MB, etc.). Each stream is independent, so I can tell which stream will receive bytes or when.

Thanks.

RyanM
  • 5,680
  • 9
  • 45
  • 55

1 Answers1

0

Use NSFileHandle and its -seekToFileOffset: method.

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
  • So you're saying this won't throw an error if the target file on disk is 0 bytes and s3 wants to write to it starting at an offset equal to 75MB? I can just tell it to seek to 75MB on a 0 byte file and write from there? Thanks – RyanM May 31 '12 at 12:12
  • It's not clearly documented for `NSFileHandle`, but it is for the underlying system call, `lseek()`. When the file position is beyond the end of the file, a write extends the file, filling with zero bytes. (That can be take considerable time, of course.) So, I'm fairly sure that `NSFileHandle` will do the same. – Ken Thomases May 31 '12 at 15:45
  • Ok. Makes sense, but if it starts filling the beginning of the file with zeros for s3 and s0 wants to write to the beginning of the file at the same time, there could be issues right (e.g. s0 starts writing and s3 overwrites with zeros)? Again, many thanks. – RyanM May 31 '12 at 18:10
  • Hmm, good question. It's the kernel which is responsible for filling with zeros and I *think* the two operations would then be atomic with respect to each other, but I'm not certain. If you know how big the file will be, you can extend it before any threads start using `ftruncate()`. At the very least, you can extend it to where s3 is to start writing, because you've decide the file will be at least that large. – Ken Thomases May 31 '12 at 21:10
  • Great. Again, makes sense. Thank you for taking the time to answer! – RyanM Jun 01 '12 at 00:38