1. Perl
  2. File input/output
  3. here

What is file locking?

If multiple people write to one file at the same time, the file will be damaged. If multiple processes write to a file in parallel, each process must be in order. The file locking mechanism allows multiple processes to securely access files in order.

File locking, also called exclusive control, is a mechanism in which multiple processes use files in order. Perl has a mechanism for locking files called flock function. (Some OSs such as Window98 cannot use flock.)

If you need to keep the order

If you want to read one file in parallel, you don't have to keep the order. It just reads, so you don't have to worry about file corruption or data inconsistencies.

You need to keep the order when multiple processes write to a single file. If the files are written in parallel without being written in order, the file will be damaged.

Also, if there are multiple processes that read and write to one file, data inconsistency will occur. Consider an access counter. Suppose the file says 0. Suppose you have a program that adds 1 to this number and writes it back. Consider the problem that arises when accessing in parallel in this case.

Process A Read - -- -- -- -- -- -- -- -- ->Write
                  0 1

Process B Read - -- -- -- -- -- -- -- -- -- -->Write
                                 0 1

File contents 0 1 1

In the case of access counters, it is clear that the above flow is not what you expected. We expect the first 0 to 2 to be added when the two processes have finished processing. To keep the data consistent, process B must wait for process A to write 1 to the file.

Advisory Lock

Perl uses the flock function to lock a file, but this function does not force a file to be locked. In fact, other processes can write to the file locked by the flock function.

For file locking to work properly, every process that attempts to access a file must use the flock function to lock the file. If there is a process that does not keep this promise, the files cannot be used in sequence.

Such locks are called advisory locks. "Keep the order. If you want to use the file, flock it. If no one is using it, you can get the right to use the file. Someone is using it. If so, please wait as you will be notified that it cannot be used now. "

Exclusive and shared locks

Lock types include exclusive locks and shared locks. Exclusive locks are used when writing and shared locks are used when reading.

Twice Opportunity to use When another process tries to lock
Shared lock When reading Allow shared locks but not exclusive locks
Exclusive lock When writing Do not allow shared or exclusive locks

It's a little confusing, but the simple answer is, "If you want to read it, you can read it by multiple people, but if you want to write it, be sure to write it by yourself."

Related Informatrion