|
楼主 |
发表于 2012-2-7 00:02:34
|
显示全部楼层
Tasks
Since the NXT supports multi-threading, a task in NXC directly corresponds to an NXT thread.
Tasks are defined using the task keyword with the syntax shown in the code sample below.
task name()
{
// the task's code is placed here
}
The name of the task may be any legal identifier. A program must always have at least one task - named "main" - which is started whenever the program is run. The body of a task consists of a list of statements.
You can start and stop tasks with the start and stop statements, which are discussed below. However, the primary mechanism for starting dependant tasks is scheduling them with either the Precedes or the Follows API function.
The StopAllTasks API function stops all currently running tasks. You can also stop all tasks using the Stop function. A task can stop itself via the ExitTo function. Finally, a task will stop itself simply by reaching the end of its body.
In the code sample below, the main task schedules a music task, a movement task, and a controller task before exiting and allowing these three tasks to start executing concurrently. The controller task waits ten seconds before stopping the music task, and then waits another five seconds before stopping all tasks to end the program.
task music() {
while (true) {
PlayTone(TONE_A4, MS_500);
Wait(MS_600);
}
}
task movement() {
while (true) {
OnFwd(OUT_A, Random(100));
Wait(Random(SEC_1));
}
}
task controller() {
Wait(SEC_10);
stop music;
Wait(SEC_5);
StopAllTasks();
}
task main() {
Precedes(music, movement, controller);
}
--------------------------------------------------------------------------------
摘自官方手册 |
|