user2820579
user2820579

Reputation: 3451

Not closed files in julia writes different output?

I have a julia program that simulate an ensemble of systems. Basically in each realization I record observables as a function of time and write, per realization, the results to a file.

I noticed just recently that I had a file where I write my results that has not the proper

close(filename)

command. Just to be sure, would there be any error in my numerics if I have not properly close the files that I use to write?

Since julia doesn't raise an error when it compiles, I would like to know if this is done implicitly by Julia

Upvotes: 3

Views: 116

Answers (2)

jch
jch

Reputation: 5651

All IOStreams will be closed and their buffers flushed before the Julia process exits. However, the time at which the IOStream will be closed is unpredictable.

The exact mechanism is as follows. The open function, which creates a file IOStream, registers a finaliser with the garbage collector. Periodically, Julia invokes the garbage collector, which destroys any unreachable data structures; if it destroys an IOStream, it runs the associated finaliser which closes the file.

Since the time at which the garbage collector is run is unpredictable, it is better to explicitly close the IOStream yourself: you should consider the finalisation mechanism as a mere additional security measure in case you forget to call close.

Upvotes: 1

IainDunning
IainDunning

Reputation: 11664

The file will be automatically closed at the end of the script (or, if its opened in a function, at the end of the function).

More precisely, it will be closed when the file pointer goes out of scope.

Even more precisely, it will be closed when the file pointer gets garbage collected.

Upvotes: 2

Related Questions