Propeller Manual

Table Of Contents
2: Spin Language Reference – COGNEW
Spin Code (Syntax 1)
To run a Spin method in another cog, the
COGNEW command needs the method name, its
parameters, and a pointer to some stack space. For example:
VAR
long SqStack[6] 'Stack space for Square cog
PUB Main | X
X := 2 'Initialize X
cognew(Square(@X), @SqStack) 'Launch square cog
<check X here> 'Loop here and check X
PUB Square(XAddr)
'Square the value at XAddr
repeat 'Repeat the following endlessly
long[XAddr] *= long[XAddr] ' Square value, store back
waitcnt(2_000_000 + cnt) ' Wait 2 million cycles
This example shows two methods, Main and Square. Main starts another cog that runs Square
endlessly, then Main can monitor the results in the X variable. Square, being run by another
cog, takes the value of
XAddr, squares it and stores the result back into XAddr, then waits for 2
million cycles before it does it again. More explanation follows, but the result is that
X starts
out as 2, and the second cog, running
Square, iteratively sets X to 4, 16, 256, 65536 and then
finally to 0 (it overflowed 32 bits), all independent of the first cog which may be checking the
value of
X or performing some other task.
The
Main method declares a local variable, X, that is set to 2 in its first line. Then Main starts a
new cog, with
COGNEW, to run the Square method in a separate cog. COGNEW’s first parameter,
Square(@X), is the Spin method to run and its required parameter; in this case we pass it the
address of the
X variable. The second parameter of COGNEW, @SqStack, is the address of stack
space reserved for the new cog. When a cog is started to run Spin code, it needs some stack
space where it can store temporary data. This example only requires 6 longs of stack space
for proper operation (see The Need for Stack Space, below, for more information).
After the
COGNEW command is executed, two cogs are running; the first is still running the Main
method and the second is starting to run the
Square method. Despite the fact that they are
using code from the same Spin object, they are running independently. The “
<check X
here>
” line can be replaced with code that uses the value of X in some way.
Propeller Manual v1.1 · Page 79