Pergunta

I have a unique problem. There are two processes (P0 and P1) trying to access one file. P0 is writing information to the file and P1 is reading the information. There is a race condition occurring between the two in which P1 is reading before P0 is finished writing. I have considered using Locks, Semaphores, etc. However, P1 exists in a set of code that I am not allowed to alter in any way, and it currently has no implementation to support the above proposed fixes.

Is there any way to remove this race condition without touching both sets of code?

Foi útil?

Solução

You can let P0 write to file A and let P1 read from file B. When P0 has completed writing the file, rename file A to file B. You'll have to make sure the rename operation is atomic though.

Outras dicas

Niels's solution is great, but may not be applicable if it's a big file with small deltas. I'm going to suggest that your solution would depend on:
a) whether P1 is locking the file and you just want to just get rid of the conflict,
b) whether you need to make sure that what P1 reads is always the updated copy with P0's changes, and
c) whether P1 honors a read-lock on the file in question.

Also, look for underlying O/S system calls to see if you can track P1's behavior from within P0 to coordinate the processes. For example, for Windows the .NET System.Diagnostics.Process class might provide some useful methods.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top