How does using the try statement avoid a race condition?

后端 未结 3 1942
终归单人心
终归单人心 2020-11-29 04:32

When determining whether or not a file exists, how does using the try statement avoid a \"race condition\"?

I\'m asking because a highly upvoted answer (update: it w

3条回答
  •  忘掉有多难
    2020-11-29 05:22

    I think what you're asking is the particular race condition where:

    1. file is opened
    2. context is switched and the file is deleted
    3. context is switched back and file operations are attempted on the "opened" file

    The way you're "protected" in this case is by putting all the file handling code in a try block, if at any point the file becomes inaccessible/corrupt your file operations will be able to fail "gracefully" via the catch block.

    Note of course modern OS's this can't happen anyway, when a file is "deleted" the delete won't take place until all open handles on the file are resolved (released)

提交回复
热议问题