Lock (statement)

Syntax

Lock [#] filenumber [,{record | [start] To end}]

Description

Locks a section of the specified file, preventing other processes from accessing that section of the file until the Unlock statement is issued.

Comments

The Lock statement requires the following parameters:

 

Parameter

Description

 

filenumber

Integer used by the Basic Control Engine to refer to the open fileā€”the number passed to the Open statement.

 

record

Long specifying which record to lock.

 

start

Long specifying the first record within a range to be locked.

 

end

Long specifying the last record within a range to be locked.

 

For sequential files, the record, start, and end parameters are ignored. The entire file is locked.

The section of the file is specified using one of the following:

 

Syntax

Description

 

No parameters

Locks the entire file (no record specification is given).

 

record

Locks the specified record number (for Random files) or byte (for Binary files).

 

to end

Locks from the beginning of the file to the specified record (for Random files) or byte (for Binary files).

 

start to end

Locks the specified range of records (for Random files) or bytes (for Binary files).

 

The lock range must be the same as that used to subsequently unlock the file range, and all locked ranges must be unlocked before the file is closed. Ranges within files are not unlocked automatically by the Basic Control Engine when your script terminates, which can cause file access problems for other processes. It is a good idea to group the Lock and Unlock statements close together in the code, both for readability and so subsequent readers can see that the lock and unlock are performed on the same range. This practice also reduces errors in file locks.

Example

This example creates test.dat and fills it with ten string variable records. These are displayed in a dialog box. The file is then reopened for read/write, and each record is locked, modified, rewritten, and unlocked. The new records are then displayed in a dialog box.

Const crlf = Chr$(13) + Chr$(10)

Sub Main()
  a$ = "This is record number: "
  b$ = "0"
  rec$ = ""

  msg1 = ""
  Open "test.dat" For Random Access Write Shared As #1
  For x = 1 To 10
    rec$ = a$ & x
    Lock #1,x
    Put #1,,rec$
    Unlock #1,x
    msg1 = msg1 & rec$ & crlf
  Next x
  Close
  MsgBox "The records are:" & crlf & msg1

  msg1 = ""
  Open "test.dat" For Random Access Read Write Shared As #1
  For x = 1 To 10
    rec$ = Mid(rec$,1,23) & (11 - x)
    Lock #1,x
    Put #1,x,rec$
    Unlock #1,x
    msg1 = msg1 & rec$ & crlf
  Next x
  MsgBox "The records are: " & crlf & msg1
  Close

  Kill "test.dat"
End Sub

See Also

Unlock (statement); Open (statement).

More information

L