Threads (taskLib.h)


Thread functions When a thread (aka. tasks) is created, the user specifies the thread function, i.e. the function that should execute in the new thread's context. A thread function has the prototype void func(int arg1, int arg2, ..., int arg10), where the argument list can be empty or contain up to 10 integers. An example of a thread function could be

void myThreadFunc(int arg1)
{
 while(true)
 {
 cout << "Hi! I am a thread function that took the argument " << arg1 << endl;
 taskDelay(1000); // sleep for 1000 ticks
 }
}

Thread creation

Threads are created using taskCreate(). When a task is created, a number of properties can be specified, most notably the thread function and it's arguments. taskCreate() returns a thread id that should be stored as it is how threads are later identified for activation, deletion, etc. Threads are created as shown below:

void myMain()
{
 ...
 int id = taskCreate( "My Task", // Name of the thread
 100, // Priority (0-255, 0 is highest)
 0, // Options (none set). See taskLib
 0x1000, // Stack size
 (FUNCPTR) myThreadFunc, // The thread function, casted to a FUNCPTR (built-in type)
 4, // Argument arg1 to myThreadFunc()
 0, 0, 0, 0, 0, 0, 0, 0, 0 // arg2 - arg9 (unused)
 );
 ...
}

Thread activation

When a thread has been created it is dormant and must be activated before it enters the collection of ready-to-run threads. This is done by a call to threadActivate() as shown below:
void myMain()
{
 ...
 int id = taskCreate(...); // Create a task (see the section "Thread creation" above)
 taskActivate(id); // Activate the recently created thread
 ...
}

Thread creation + activation in one go

Threads can be created and activated in one go by using taskSpawn(). The use is exactly the same as for taskCreate() as shown above, the only difference is that a thread created using taskSpawn() is instantly activated. In effect, taskSpawn() = taskCreate() + taskActivate().

Thread suspension

Threads may suspend themselves (i.e. "sleep") for a given number of ticks by calling taskDelay(). This was demonstrated in the Thread Functions section above.

Thread deletion

Threads can be deleted by using taskDelete() as shown below:

 void myMain()
 {
 ...
 int id = taskCreate(...); // Create a task (see the section "Thread creation" above)
 taskActivate(id); // Activate the recently created thread
 
 ...
 
 taskDelete(id);    // delete the thread
 }