www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Safely writing to the same file in parallel foreach loop

Suppose that I've got a foreach loop in which I write output to a file:

     auto f = File("test.txt", "w"); f.close();  // to start with a blank file
     foreach(i; iota(0, 100))
         f = File("test.txt", "a");

I'm guessing it is at least potentially unsafe to parallelize the loop without 
also considering the file interactions:

     foreach(i; parallel(iota(0, 100), 20))
         f = File("test.txt", "a");  // What happens if 2 threads want to
         f.writeln(i);               // open this file at the same time?

... so, is there a way that I can ensure that the file appending takes place 
successfully but also safely in each thread?  Let's assume that I don't care 
about the order of writing, only that it takes place.
Nov 14 2012