Threads
Threads are supported by a number of special commands.
To declare a new thread a syntax similar to the declaration of functions are used:
thread myThread():
# Do some stuff
return False
end
A couple of things should be noted. First of all, a thread cannot take any parameters, and so the parentheses in the declaration must be empty. Second, although a return statement is allowed in the thread, the value returned is discarded, and cannot be accessed from outside the thread. A thread can contain other threads, the same way a function can contain other functions. Threads can in other words be nested, allowing for a thread hierarchy to be formed.
To run a thread use the following syntax:
thread myThread():
# Do some stuff
return False
end
thrd = run myThread()
The value returned by the run
command is a handle to the running thread. This handle can be used to interact with a running thread. The run command spawns from the new thread, and then executes the instruction following the run
instruction.
A thread can only wait for a running thread spawned by itself. To wait for a running thread to finish, use the join command:
thread myThread():
# Do some stuff
return False
end
thrd = run myThread()
join thrd
This halts the calling threads execution, until the specified thread finishes its execution. If the thread is already finished, the statement has no effect.
To kill a running thread, use the kill
command:
thread myThread():
# Do some stuff
return False
end
thrd = run myThread()
kill thrd
After the call to kill, the thread is stopped, and the thread handle is no longer valid. If the thread has children, these are killed as well.
To protect against race conditions and other thread-related issues, support for critical sections is provided. A critical section ensures the enclosed code can finish running before another thread can start running. The previous statement is always true, unless a time-demanding command is present within the scope of the critical section. In such a case, another thread will be allowed to run. Time-demanding commands include sleep, sync, move-commands, and socketRead. Therefore, it is important to keep the critical section as short as possible. The syntax is as follows:
thread myThread():
enter_critical
# Do some stuff
exit_critical
return False
end