COBOL Manual for TNS/E Programs (H06.03+)
Disk Input and Output
HP COBOL Manual for TNS/E Programs—520347-003
28-38
Locking and Unlocking Files and Records
Locking and Unlocking Files and Records
The most complete way for a process to lock a file is to open the file for exclusive
access (open it with the exclusion mode EXCLUSIVE). This strategy prevents all other
processes from reading or writing the file.
If it is not feasible for one process to have exclusive control of a file for when it has the
file open, there are alternatives.
One alternative is protected access. When a process opens a file for protected access
(opens it with the exclusion mode PROTECTED), other processes can read and write
the file while the opening process has it open, but cannot write the file until the opening
process closes the file.
Another alternative is shared access. When a process opens a file for shared access
(opens it with the exclusion mode SHARED), other processes can read and write the
file while the opening process has it open.
When a file is open for shared access and one process needs exclusive access to the
file temporarily, that process can lock the file with a LOCKFILE statement, operate on
it, and then unlock it with an UNLOCKFILE statement. If a process only needs
temporary exclusive access to a record of the file, the process can temporarily lock the
record with a READ statement with a LOCK phrase and then unlock it with an
UNLOCKRECORD statement.
To avoid deadlock when processes share and lock files, have each process lock and
unlock records and files in the same sequence.
Setting Time Limits on Input-Output Operations
Even when each program that shares files carefully arranges to lock files and records
in the same order, a newly introduced program or a change to an existing program can
fail to conform and cause deadlock. In HP COBOL, you can prevent this deadlock by
using the TIME LIMITS phrase with the statements OPEN, START, READ, and
LOCKFILE.
Without the TIME LIMITS phrase, if your process attempts to open a file, establish a
starting position in a file, read a file, or lock a file and that file or the necessary record
in that file is already locked, the process suspends activity until the lock is removed.
With the TIME LIMITS phrase, you can specify a time limit on the suspension. If the
time expires before the inhibiting lock is removed, the file operation terminates with file
status code “30” and GUARDIAN-ERR special register value 40. The program can
diagnose the failure of the file operation and either retry the operation or abandon the
current group of operations to allow another process to complete its operations.
Note. If a process is protected by TMF, all locks are retained (despite unlocking statements)
until the current transaction is completed or backed out.










