Compare-and-Swap over POSIX-compliant filesystem objects

前端 未结 2 557
我寻月下人不归
我寻月下人不归 2021-01-12 17:44

There are several operations which POSIX-compliant operating systems can do atomically with filesystem objects (files and folders). Here is a list of such presumably atomic

2条回答
  •  -上瘾入骨i
    2021-01-12 18:01

    If you consider fcntl(2) in your list of atomic operations, you can easily build a general mutex primitive. I use the flock(1) command line tool to do this in shell scripts regularly. (flock(1) is part of the util-linux-ng package.)

    flock(2) is not specified by POSIX but fcntl(2) is. I think flock(1) may use fcntl(2) in some cases (e.g. NFS).

    So the algorithm is something like:

      1. Do a non-blocking fcntl() on some file that is unique to the resource you want to manipulate. This may be the data file itself, or some empty file that every process agrees to use as the mutex object.
    • 2a. If the fcntl is successful, swap the data in the file.
    • 2b. If the fcntl is not successful, don't touch the data file.
      1. Release the fcntl on the file.

    You could of course do a blocking fcntl(2), but there won't be any way to know what order each process blocks and gets woken up, so whether this is appropriate depends on the application.

    Note that fcntl(2) is advisory, so it won't prevent unwanted manipulation of the data file.

提交回复
热议问题