1

In my last job interview, I was asked to make a program that sorts data in a huge file. I implemented it using c++ WinApi. Everything was ok until interviewer noticed that i wrote to the file concurrently through a single file handle. He told that i had to synchronize writes with a mutex. I tried to argue that every thread wrote data in its own file area explicitly specifing offset from the file beginning so there was no need in synchronization, it was useless.

Questions:

  1. Is it safe to write (WriteFile) to a file concurrently using a single handle, assuming that a every thread has its own file part?
  2. Where i can find any information about it?
sliser
  • 1,645
  • 11
  • 15
  • 1
    You can specify a position in OVERLAPPED structure – sliser Dec 12 '14 at 16:18
  • possible duplicate of [WriteFile thread safety](http://stackoverflow.com/questions/15894082/writefile-thread-safety) – SLaks Dec 12 '14 at 16:21
  • See also [Synchronous and Asynchronous I/O](http://msdn.microsoft.com/en-us/library/windows/desktop/aa365683(v=vs.85).aspx). I know that what you're asking is safe if you're using an `OVERLAPPED` structure and you opened the file with `FILE_FLAG_OVERLAPPED`. Whether it's okay if you didn't open the file for asynchronous I/O, I'm not certain. – Jim Mischel Dec 12 '14 at 18:44
  • 1
    If you don't use overlapped I/O, then each thread needs to have its own handle to the file, so that each thread maintains its own offset into the file. Multiple handles can be open to the same underlying file. As long as the threads do not overlap each other's sections of the file, then you don't need to synchronize the writes when using multiple handles, only when using a single shared handle. – Remy Lebeau Dec 12 '14 at 22:55

0 Answers0