Imagine the following Perl code (here in pseudo code):
successfully acquired flock for FILEHANDLER # line 1 some error or maybe simply a call to exit()
When the program exits, the OS automatically releases all locks acquired by the program and closes all files opened by the program.