Pattern: How to start a thread of execution in Fantom
In Fantom, how do you start a new thread of execution? The pattern below is very simple and nice.
The code above might seem a little odd at first. All that it does is to create an Actor with a code block that will execute the doSomething method. By sending a dummy message (".send(null)"), the Actor instance is started.
The key here is that sending a dummy message to an Actor starts the Actor. This same trick may be applicable to other Actor based languages as well.
const class Main {
Void main() {
svc := Actor(ActorPool()) { doSomething }.send(null)
}
Obj? doSomething() {
// Do something like binding to a port and listening for requests.
// Or you can call another method that does that.
return null
}
}
The code above might seem a little odd at first. All that it does is to create an Actor with a code block that will execute the doSomething method. By sending a dummy message (".send(null)"), the Actor instance is started.
The key here is that sending a dummy message to an Actor starts the Actor. This same trick may be applicable to other Actor based languages as well.
Comments