Pure, of course:
you have lost the multithreading processing by this technique,
since your threads are working nonparallel...
I would solve it like following:
- Control the file access by a critical section (for thread 1 und 3)
- Allocate a protected by a second critical section the whole-sized buffer
- Control the "clusters" of the buffer in a cluster list protected by a third critical section
2a. The first thread read a block by block from the file in its loop and
2aa. fill the buffer by the read cluster
2ab. make an entry in the list with the flag "ReadyToModify = true, BlockOffsetInBuffer = x, BlockLengthInBuffer = y"
2b. The second thread iterate the list to find the next entry marked by "ReadyToModify = 1"
2ba. read the cluster from the buffer to a local buffer
2bb. modify the local buffer
2bc. fill the buffer by local modified cluster
2bd. set the list entry flag "ReadyToSave = 1"
2c. The third thread iterate the list to find the next entry marked by "ReadyToSave = 1"
2ca. read the cluster from the buffer to a local buffer
2cb. save the local buffer in to the file