Can asynchronous calls to WriteFile result in torn writes?

Viewed 293

I have hypothetical scenario where a file handle opened in asynchronous mode, and some threads which are appending to that file handle. They append by setting the Offset and OffsetHigh parts of the OVERLAPPED structure to 0xFFFFFFFF, as documented in the MSDN article for WriteFile.

Can I issue a second write in append mode like this before the first append completes, and expect the file to contain the entire contents of the first append followed by the entire contents of the second append? Or must I wait to issue the following asynchronous write until the previous write completes?

2 Answers

Yes. It works. I worked at a company that used a similar scheme, although to get their seek calls to work each time, the predefined the file at a known size (about 2Gb...) then truncated the file at the end.

However, you can just "append" by going to the right location before each write. You'll have to handle the position yourself though.

And also each thread must access the file atomically, "of course."

A simple example:

lock mutex
seek to position
write data
position += data size
unlock mutex

Of course here I assume that the file is properly opened before you call this function from any thread.

The one thing that you cannot do, unless you create a large file first (which is very fast since files with all zeroes are created virtually), is seek at a position depending on something such as a frame number. So if thread 3 wants to write at "size * 3" and that happens before thread 2 writes at "size * 2" then the seek() will fail...

Related