LOCKSET

Command: Set lock to true and get its previous state.

((PUBPRI))
  LOCKSET ( ID )


Returns: Previous state of lock (TRUE or FALSE).

  • ID is the ID (0 – 7) of the lock to set to TRUE.

Explanation

LOCKSET is one of four lock commands (LOCKNEW, LOCKRET, LOCKSET, and LOCKCLR) used to manage resources that are user-defined and deemed mutually exclusive. LOCKSET sets lock ID to TRUE and retrieves the previous state of that lock (TRUE or FALSE).

See Locks for information on the typical use of locks and the LOCKxxx commands.

The following assumes that a cog (either this one or another) has already checked out a lock using LOCKNEW and shared the ID with this cog, which saved it as SemID. It also assumes this cog has an array of longs called LocalData.

PUB ReadResource | Idx 
  repeat until not lockset(SemID)           'wait until we lock the resource
  repeat Idx from 0 to 9                    'read all 10 longs of resource
    LocalData[Idx] := long[Idx]
  lockclr(SemID)                            'unlock the resource 

PUB WriteResource | Idx 
  repeat until not lockset(SemID)           'wait until we lock the resource
  repeat Idx from 0 to 9                    'write all 10 longs to resource
    long[Idx] := LocalData[Idx]
  lockclr(SemID)                            'unlock the resource 

Both of these methods, ReadResource and WriteResource, follow the same rules before and after accessing the resource. First, they wait indefinitely at the first REPEAT loop until it has locked the resource; i.e., it has successfully "set" the associated lock. If LOCKSET returns TRUE, the condition "until not lockset…" is false, meaning that some other cog is currently accessing the resource, so that first REPEAT loop tries again. If LOCKSET returns FALSE, the condition "until not lockset…" is true, meaning we have "locked the resource" and the first REPEAT loop ends. The second REPEAT loop in each method reads or writes the resource, via the long[Idx] and LocalData[Idx] statements. The last line of each method, lockclr(SemID), clears the resource's associated lock to FALSE, logically unlocking or releasing the resource for others to use.

See LOCKNEW, LOCKRET, and LOCKCLR for more information.

Unless otherwise noted, content on this site is licensed under the
Creative Commons Attribution-ShareAlike 4.0 International License.