Propeller Manual

Table Of Contents
LOCKNEW – Spin Language Reference
Page 122 · Propeller Manual v1.1
LOCKNEW
Command: Check out a new lock and get its ID.
((PUB PRI))
LOCKNEW
Returns: ID (0-7) of the lock checked out, or -1 if none were available.
Explanation
LOCKNEW is one of four lock commands (LOCKNEW, LOCKRET, T LOCKSETT, and LOCKCLR) used to
manage resources that are user-defined and deemed mutually exclusive.
LOCKNEW checks out a
unique lock, from the Hub, and retrieves the ID of that lock. If no locks were available,
LOCKNEW returns -1.
About Locks
A lock is a semaphore mechanism that is used to communicate between two or more entities.
In the Propeller chip, a lock is simply one of eight global bits in a protected register within
the Hub. The Hub maintains an inventory of which locks are in use and their current states.
Cogs can check out, set, clear, and return locks as needed during run time to indicate whether
a custom shared item, such as a block of memory, is available or not. Since locks are
managed by the Hub only one cog can affect them at a time, making this an effective control
mechanism.
In applications where two or more cogs are sharing the same memory, a tool such as a lock
may be required to prevent catastrophic collisions from occurring. The Hub prevents such
collisions from occurring on elemental data (such a byte, word or long) at every moment in
time, but it cannot prevent “logical” collisions on blocks of multiple elements (such as a
block of bytes, words, longs or any combination of these). For example, if two or more cogs
are sharing a single byte of main memory, each one is guaranteed exclusive access to that
byte by nature of the Hub. But if those two cogs share multiple bytes of main memory, the
Hub can not prevent one cog from writing a few of those bytes while another cog is reading
all of them; all cogs’ interactions with those bytes may be interleaved in time. In this case,
the developer should design each process (in each cog that shares this memory) so that they
cooperatively share the memory block in a non-destructive way. Locks serve as flags that
notify each cog when a memory block is safe to manipulate or not.