July 2018
Intermediate to advanced
266 pages
7h 11m
English
Say that we need to modify a counter safely from many different threads. First, let's create a new class. In that class, we can have a private counter and a private single-thread dispatcher, with a function to retrieve the current value of the counter:
private var counter = 0private val context = newSingleThreadContext("counterActor")fun getCounter() = counter
Now that we have encapsulated the value of the counter, we simply need to add an actor that will increase the value upon each received message:
val actorCounter = actor<Void?>(context) { for (msg in channel) { counter++ }}
Because we don't actually use the message being sent, we can simply set the type of the actor to Void?, so that the caller can send null. Now we ...
Read now
Unlock full access