Actor and Distributed Programming
Concurrent programming and distributed programming are becoming increasingly important in multi-core and many-core hardware environments. Support for these capabilities has been considered since the early stage of Cangjie language design, and the design and prototype jobs have been preliminarily completed. These capabilities will be available in the near future.
With the built-in Actor feature and support for the type system in the Cangjie language, a secure and intuitive concurrent and distributed model can be provided for developers.
Actor is an abstract program concept used for concurrent operations. It is essentially used to create an operation instance and respond to a received message. For example, a newly created Actor sends a message to another Actor, and specifies the behavior to be generated when the next message is received. In this way, communication in concurrent threads is based on policies in these messages, thereby avoiding data race.
In the following simple example, the actor
keyword is used to define Account
as the Actor type, an instance function performWithdraw
, and a receiver function withdraw
. The receiver function can receive and process messages, and the instance function can access the internal status of the Actor.
actor Account {
instance var balance: Int64
init(x: Int64) {
this.balance = x
}
instance func performWithdraw(amount: Int64): Unit {
balance -= amount
}
receiver func withdraw(amount: Int64): Bool {
if (this.balance < amount) {
return false
} else {
this.performWithdraw(amount)
return true
}
}
}
It is worth mentioning that Cangjie's Actor is designed to support concurrent programming and distributed programming with a unified language feature. This enables developers to write concurrent or distributed programs using methods they are familiar with, and then easily move the programs to a distributed (for example, cluster) environment.