Propeller Manual

Table Of Contents
2: Spin Language Reference – LOCKNEW
Propeller Manual v1.1 · Page 123
Using LOCKNEW
A user-defined, mutually exclusive resource should be initially set up by a cog, then that
same cog should use
LOCKNEW to check out a unique lock in which to manage that resource
and pass the ID of that lock to any other cogs that require it. For example:
VAR
byte SemID
PUB SetupSharedResource
<code to set up user-defined, shared resource here>
if (SemID := locknew) == -1
<error, no locks available>
else
<share SemID's value with other cogs>
The example above calls LOCKNEW and stores the result in SemID. If that result is -1, an error
occurs. If the
SemID is not -1, then a valid lock was checked out and that SemID needs to be
shared with other cogs along with the address of the resource that
SemID is used for. The
method used to communicate the
SemID and resource address depends on the application, but
typically they are both passed as parameters to the Spin method that is launched into a cog, or
as the
PAR parameter when launching an assembly routine into a cog. See COGNEW, page 78.
Suggested Rules for Locks
The following are the suggested rules for using locks.
Objects needing a lock to manage a user-defined, mutually exclusive resource should
check out a lock using
LOCKNEW and save the ID returned, we’ll call it SemID here.
Only one cog should check out this lock. The cog that checked out the lock must
communicate
SemID to all other cogs that will use the resource.
Any cog that needs to access the resource must first successfully set the lock
SemID.
A successful “set” is when
LOCKSET(SemID) returns FALSE; i.e., the lock was not
already set. If
LOCKSET returned TRUE, then another cog must be accessing the
resource; you must wait and try again later to get a successful “set”.
T
The cog that has achieved a successful “set” can manipulate the resource as
necessary. When done, it must clear the lock via
LOCKCLR(SemID) so another cog can
have access to the resource. In a well-behaved system, the result of
LOCKCLR can be
ignored here since this cog is the only one with the logical right to clear it.