File segment/section/record locks in Linux threads

前端 未结 4 1748
萌比男神i
萌比男神i 2021-01-28 16:42

I have a multi-threaded process where a file is shared (read and written) by multiple threads. Is there any way a thread can lock one file segment so that other threads cannot a

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-28 17:36

    Yes - but not with the same mechanism. You'll have to use something like pthread mutexes, and keep track of the bookkeeping yourself.

    Possible outline for how to make this work

    • Wait on and claim a process-level mutex over a bookkeeping structure
      • make sure no other threads within your process are trying to use that segment
      • mark yourself as using the file segment
    • Release the process-level mutex

    • Grab fnctl lock for process (if necessary)

    • Do your writing
    • Release fnctl lock to allow other processes to use the segment (if necessary)

    • Wait again on process-levelbookkeeping structure mutex (may not be necessary if you can mark it unused atomically)

      • mark segment as unused within your process.
    • Release process-level mutex

提交回复
热议问题