Subroutines

Subroutines

Subroutines allow a single copy of some code to be shared between several different callers. This makes subroutines much more space efficient than macro functions. Subroutines are defined using the subroutine keyword with the following syntax:

 subroutine name
   // body of subroutine
   return // subroutines must end with a return statement
 ends

A subroutine is just a special type of thread that is designed to be called explicitly by other threads or subroutines. Its name can be any legal identifier. Subroutines are not scheduled to run via the same mechanism that is used with threads. Instead, subroutines and threads execute other subroutines by using the call statement (described in the Statements section).

 thread main
   // body of main thread goes here
   call mySub // compiler handles subroutine return address
   exit // finalize execution (details handled by the compiler)
 endt

 subroutine mySub
   // body of subroutine goes here 
   return // compiler handles the subroutine return address
 ends

You can pass arguments into and out of subroutines using global variables. If a subroutine is designed to be used by concurrently executing threads then calls to the subroutine must be protected by acquiring a mutex prior to the subroutine call and releasing the mutex after the call.

You can also call a thread as a subroutine using a slightly different syntax. This technique is required if you want to call a subroutine which executes two threads simultaneously. The subcall and subret statements must be used instead of call and return. You also must provide a global variable to store the return address as shown in the sample code below.

 thread main
   // thread body goes here
   acquire ssMutex
   call SharedSub // automatic return address
   release ssMutex
   // calling a thread as a subroutine
   subcall AnotherSub, anothersub_returnaddress
   exit
 endt

 subroutine SharedSub
   // subroutine body goes here
   return // return is required as the last operation
 ends

 thread AnotherSub
   // threads can be subroutines too
   subret anothersub_returnaddress // manual return address
 endt

After the subroutine completes executing, it returns back to the calling routine and program execution continues with the next statement following the subroutine call. The maximum number of threads and subroutines supported by the NXT firmware is 256.


Generated by  doxygen 1.6.2