Upload
weaveworks
View
1.302
Download
0
Embed Size (px)
Citation preview
An Actor Model in GoBryan Boreham, Weaveworks@bboreham
According to Wikipedia…
The actor model in computer science is a mathematical model of concurrent computation that
treats "actors" as the universal primitives of concurrent computation.
Actors’ Advocacy
• Good for highly concurrent systems
• Easier to write
• Easier to reason about
This has been a learning experience
Some predictions
• I’ll get to those later
My life as a Gopher
ConnectionMaker
Weave Net ConnectionMaker
ConnectionMaker
Weave Net ConnectionMaker
ConnectionMaker
Weave Net ConnectionMaker
ConnectionMaker Properties
• Async between callers and actions
• Sync during connection attempts
• Timer-driven events
Actor
Actors
Actor Outline in Go
• Actor → struct + goroutine
• Mailbox → chan
func StartActor() *Actor {ch := make(chan action, size)actor := &Actor{ ... }go actor.actorLoop(ch)return actor
}
func (actor *Actor) DoSomething() {actor.actionChan <- something
}
func (actor *Actor) actorLoop( ch <-chan action) {
for {action := <-ch// deal with action
}}
🤔
🤔
ConnectionMaker in Go
type action func()
func (cm *ConnectionMaker) Add(address string) {cm.actionChan <- func() {
cm.addConnection(address)}
}
ConnectionMaker Loop
func (cm *ConnectionMaker) actorLoop(ch <-chan action) {timer := time.NewTimer(duration)for {
select {case action := <-ch:
action()case <-timer.C:
retryConnections()}
}}
Actions with return values
func (cm *ConnectionMaker) String() string {resultChan := make(chan string, 0)cm.actionChan <- func() {
resultChan <- cm.status()}return <-resultChan
}
What size should the chan be?
• 0
• 1
• N
• ∞
Non-blocking send
func (actor *SomeActor) TryTo(something) {select {case actor.actionChan <- func() {
// do the thing }:default:
// chan is full; throw it away }
}
Back to the theory
• An actor can designate the behaviour to be used for the next message it receives.
• Messages are sent to actors at addresses • Compare CSP: processes are anonymous and
channels are named • We use a pointer to the actor as its address
• Unbounded nondeterminism
In Practice
Pro:
• No lock/unlock
• Simple model
• Identifies goroutines
Con:
• Debugging/testing
• Single reader/writer
• No framework!
Deadlock, Feb 15 2015
localPeer.queryLoop
connection.queryLoop
handleAddConnection
connection.sendGossip
Messagehandle
SetEstablished
localPeer.ConnEstablished
chan
chan
Predictions
• You’ll say “just use a mutex”
• You’ll say “that’s what I’m doing anyway”
Summary
• “Do not communicate by sharing memory; instead, share memory by communicating” - Effective Go
• Go provides the components to work in an actor style • No framework - just type in a few lines
• Departs from Actor theory in a few ways
• In use in production for two years - http://github.com/weaveworks/mesh
Thank You
Gopher images by Renee French http://reneefrench.blogspot.com/