文件段/条/ Linux中的线程记录锁定 [英] File segment/section/record locks in Linux threads
问题描述
我有一个多线程的过程,其中一个文件被多个线程共享(读取和写入)。有什么办法一个线程可以锁定一个文件段以便其他线程不能访问它?
我曾尝试的fcntl(FD,F_SETLKW,&安培;羊群)
,但这种锁仅适用于过程,而不是线程(锁在一个进程中的所有线程间共享)。
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 access it?
I have tried fcntl(fd, F_SETLKW, &flock)
, but this lock only works for processes, not threads (a lock is shared between all threads in an process).
推荐答案
是 - 但不是相同的机制。你将不得不使用类似的pthread互斥,并跟踪簿记自己。
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
- 等待并声称进程级互斥通过簿记结构
- 确保您的过程中没有其他线程试图使用该段
- 标记为自己使用的文件段
释放进程级互斥
抓斗fnctl锁定进程(如果需要)
Grab fnctl lock for process (if necessary)
推出fnctl锁,以允许其他进程使用段(如有必要)
Release fnctl lock to allow other processes to use the segment (if necessary)
在过程levelbookkeeping结构互斥再次等待(可能没有必要,如果你可以将其标记未使用的原子)
Wait again on process-levelbookkeeping structure mutex (may not be necessary if you can mark it unused atomically)
- 标记细分的过程中为未使用。
这篇关于文件段/条/ Linux中的线程记录锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!