Last active
May 27, 2020 19:30
-
-
Save Oppodelldog/7d9b7f5f7d53c5ad96f784ced6c54b67 to your computer and use it in GitHub Desktop.
one sample of non blocking coroutine safe boolean access
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 | |
import ( | |
"fmt" | |
"time" | |
) | |
func newT() T { | |
t := make(T) | |
go func() { | |
var b bool | |
for { | |
select { | |
case b = <-t: | |
case t <- b: | |
} | |
} | |
}() | |
return t | |
} | |
type T chan bool | |
func (t T) Get() bool { | |
return <-t | |
} | |
func (t T) Set(v bool) { | |
t <- v | |
} | |
func main() { | |
t := newT() | |
t.Set(false) | |
fmt.Println(t.Get()) | |
t.Set(true) | |
fmt.Println(t.Get()) | |
time.Sleep(100 * time.Millisecond) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment