Last active
April 17, 2018 13:37
-
-
Save WhisperingChaos/4c2e923288b673b67ddb1ae62f98ffd3 to your computer and use it in GitHub Desktop.
Exploring goroutine ordering explicit happen before.
This file contains hidden or 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 | |
/* | |
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