0

fcntl using code

Hi. I'm trying to access a file with multiple threads, trying to get synchronization with record lock(fcntl).

The problem is, fcntl doesn't lock the file.

result

I've tried: each threads to have own file descriptor/one file descriptor(global), checked the parameters of fcntl, but no reason or solution found.

Is there anything wrong with the function I've write? or maybe something to know when using fcntl in multi-threads?

MIN
  • 1
  • Please don't post code as images: include the text in the question and use the _Code Sample_ markup (the `{}` button) to mark it as code. Regarding the question itself: is the file you're trying to access a local file or are you accessing it across some kind of network? – TripeHound May 09 '21 at 09:40
  • Welcome to Stack Overflow. Please read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly please learn how to create a [mcve] that you can show inside the question itself. – Some programmer dude May 09 '21 at 09:41
  • I see I should have put the code with markup and read the notification first. Thank you. The file is a local file. – MIN May 09 '21 at 09:49
  • Also see this question: https://stackoverflow.com/questions/12993120/file-segment-section-record-locks-in-linux-threads – tofro May 09 '21 at 09:59

1 Answers1

2

fcntl implements process-level locking. Apparently, all your threads live in the same process, so there's no in-between locks (or, put another way: All threads within a process share the same locks).

The Linux man page says:

The threads in a process share locks. In other words, a multithreaded program can't use record locking to ensure that threads don't simultaneously access the same region of a file.

tofro
  • 5,640
  • 14
  • 31
  • I see... so it is rather not appropriate to use record locking in a single process, multithreaded program. thank you. – MIN May 09 '21 at 09:52
  • Well, it is - to defend your records against concurrent access from outside of the process. What you need to do in addition within your own process, is to maintain concurrent access with your own, internal, locking structure, and some mutexes between your threads. The question I linked above in my comment has some useful proposals. – tofro May 09 '21 at 10:03