Created
August 20, 2016 21:48
-
-
Save gallir/2d69477881c0d1b51114c98498b3e978 to your computer and use it in GitHub Desktop.
an actor in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
var ( | |
requestToActor chan int | |
responseFromActor chan int | |
) | |
const ( | |
adders = 1000 | |
operations = 1000 | |
) | |
func main() { | |
requestToActor = make(chan int) | |
responseFromActor = make(chan int) | |
done := make(chan bool) | |
// Launch tha actor | |
go actor() | |
// Creates threads that will increment the counter | |
for i := 0; i < adders; i++ { | |
go adder(operations, done) // Do increments | |
} | |
// Wait for all adders | |
for i := 0; i < adders; i++ { | |
<-done | |
} | |
// Get the value of the actor's counter | |
requestToActor <- 0 // Increment by zero ;) | |
value := <-responseFromActor // Just discard the result | |
fmt.Printf("The final value of counter is %d\n", value) | |
} | |
func actor() { | |
counter := 0 // This a variable that will be incremented "concurrently" (not) by an actor ;) | |
for { | |
incr := <-requestToActor | |
counter += incr | |
responseFromActor <- counter | |
} | |
} | |
func adder(operations int, done chan bool) { | |
for i := 0; i < operations; i++ { | |
requestToActor <- 1 // Increment by 1 | |
<-responseFromActor // Just discard the result | |
} | |
done <- true // I finished | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment