Min_
Min_

Reputation: 1

fcntl not working (doesn't lock the file) in multi-threaded programme

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?

Upvotes: 0

Views: 1000

Answers (2)

alan_wang
alan_wang

Reputation: 855

fcntl is process level, you can use flock

Upvotes: 0

tofro
tofro

Reputation: 6073

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.

Upvotes: 3

Related Questions