In general, you can partition the loop to delegate to "workers" and have each instance pipe the output to different files, each corresponding to an output stream. This avoids the need for mutual exclusion around your output streams. If you need to aggregate logs then run some log aggregator.