-
Notifications
You must be signed in to change notification settings - Fork 3
Threading
Hassium supports builtin threading. This means that two tasks or functions can be executing side-by-side on different OS threads. Threads created also have access to their creator's stack frame, much like closures/lambdas. This page shall describe the nuances of threading in Hassium.
Threads are declared as expressions in Hassium using the thread
keyword. The resulting thread is then pushed to the stack so that it can be assigned to a variable, returned, etc. Here is an example of a new thread declaration:
func main () {
t = thread {
println ("Hello from another thread!");
}
}
When ran, this code should do nothing, since the new thread object has just been assigned to the variable t
. We can start the thread using the start
attribute of the thread object:
func main () {
t = thread {
println ("Hello from another thread!");
}
t.start ();
}
This code should print out the message Hello from another thread!
.
In order to see the true power of threading, let's create a program that will start two threads at once. We'll declare a function that will return a thread to the caller, so that it can be started:
func getThread (name : string) : thread {
return thread {
while (true) {
print (name);
}
}
}
We can pass in a string parameter to the thread, which will be saved in the stack frame that the returned thread holds. Now from the main method we can call two of these threads and see the output:
func main () {
getThread ("one").start ();
getThread ("two").start ();
}
This should infinitely produce the output of onetwoonetwoonetwoonetwoonetwo
as both threads are trying to write their variables to the console at the same time.
If a thread body contains a return
statement, you can access the value returned from the thread's body using the returnValue
property. Here is an example of a function that returns a thread thread that returns a random integer:
use Math;
func getThread () : thread {
return thread {
return new Random ().nextInt ();
}
}
From the main
method we can call this thread and get the random value returned:
func main () {
th = getThread ();
th.start ();
while (th.isAlive) ; # Hang until the thread is done.
println (th.returnValue);
}