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.
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.