Python: writing to file with parallel processing

Status
Not open for further replies.

Soriak

Ars Legatus Legionis
13,069
Subscriptor
I'm running some simulations using the joblib library. For that, I have some number of parameter combinations, each of which I run 100,000 times. I'd now like to write the result of each simulation to a CSV file.

The problem I've noticed is that if I append the file with each of the 100k runs (one at a time), it can happen that two threads try to save to the file at the same time and some row(s) end up empty. However, if I just collect the results until the very end, it takes up massive amounts of memory. This would end up with a list of millions of elements... not a good idea.

Is there an elegant way of solving this? In particular, can I just "lock" a file while one thread writes to it, and other threads will check if it's locked (and keep checking if it is)? Writing 100k rows at a time should be fine, so I could write to the file once for each parameter combination.
 

herko

Tone down Your Control issues.
7,012
Moderator
This is roughly what I do (not tested, written from memory, etc)

Code:
import multiprocessing

def Writer(dest_filename, some_queue, some_stop_token):
    with open(dest_filename, 'w') as dest_file:
        while True: 
            line = some_queue.get()
            if line == some_stop_token:
                return
            dest_file.write(line)

def the_job(some_queue):
    for item in something:
        result = process(item)
        some_queue.put(result)


if __name__ == "__main__":
   queue = multiprocessing.Queue()

   STOP_TOKEN="STOP!!!"

   writer_process = multiprocessing.Process(target = Writer, args=("output.txt", queue, STOP_TOKEN))
   writer_process.start()

   # Dispatch all the jobs

   # Make sure the jobs are finished
   
   queue.put(STOP_TOKEN)
   writer_process.join()
   # There, your file was written.
 
Status
Not open for further replies.