Skip to content

Instantly share code, notes, and snippets.

@WhisperingChaos
Last active April 17, 2018 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WhisperingChaos/4c2e923288b673b67ddb1ae62f98ffd3 to your computer and use it in GitHub Desktop.
Save WhisperingChaos/4c2e923288b673b67ddb1ae62f98ffd3 to your computer and use it in GitHub Desktop.
Exploring goroutine ordering explicit happen before.
package main
/*
Exploring concept of "Happens Before" using channels to impose order on
selection of "next" goroutine from runtime scheduling queue. Trying
to enforce "fairness" whose meaning in this situation guarantees execution
of all goroutines, avoiding goroutine starvation/barging explained
here: https://github.com/golang/go/issues/11506.
go PlayGound: https://play.golang.org/p/4sGKDepzqaV
*/
import (
"fmt"
"time"
)
func main() {
read := make(chan bool)
term := make(chan bool)
start := make(chan bool)
hb := make( chan bool)
go reader(read, start, term, "1", hb, nil)
start <-true
go reader(read, start, term, "2", nil, hb)
start <-true
for i := 0; i < 100; i++ {
// Sleep of 0
time.Sleep(0 * time.Nanosecond)
read <- true
}
close(read)
<-term
<-term
}
func reader(read chan bool, start chan bool, term chan bool, tag string, hb chan bool, ha chan bool) {
var tot int
<-start
for range read {
tot++
fmt.Printf("Reader With Start: %s\n", tag)
if hb != nil { hb <- true}
if ha != nil { <-ha}
}
fmt.Printf("Reader With Start: %s Total: %d\n", tag, tot)
term <- true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment