Last active
November 19, 2019 07:33
-
-
Save whitekid/6cfd571c21b2a1687242e0141418024e to your computer and use it in GitHub Desktop.
chan broadcast
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" | |
"sync" | |
) | |
func chanEvent1() { | |
ch := make(chan struct{}) | |
var wg sync.WaitGroup | |
defer wg.Wait() | |
defer close(ch) | |
for i := 0; i < 5; i++ { | |
wg.Add(1) | |
go func(i int) { | |
defer wg.Done() | |
defer fmt.Printf("%d: chan closed\n", i) | |
<-ch | |
}(i) | |
} | |
} |
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" | |
"sync" | |
"time" | |
) | |
type Object struct { | |
notify chan struct{} | |
l sync.Mutex | |
} | |
func (o *Object) Notify() <-chan struct{} { | |
o.l.Lock() | |
defer o.l.Unlock() | |
if o.notify == nil { | |
o.notify = make(chan struct{}, 5) | |
} | |
return o.notify | |
} | |
func (o *Object) Done() { | |
if o.notify != nil { | |
o.l.Lock() | |
defer o.l.Unlock() | |
close(o.notify) | |
o.notify = nil | |
} | |
} | |
func chanEvent2() { | |
var o Object | |
var wg sync.WaitGroup | |
defer wg.Wait() | |
defer o.Done() | |
for i := 0; i < 5; i++ { | |
wg.Add(1) | |
go func(i int) { | |
defer wg.Done() | |
defer fmt.Printf("%d: chan closed\n", i) | |
<-o.Notify() | |
}(i) | |
} | |
time.Sleep(time.Millisecond) | |
} |
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 | |
func main() { | |
for i := 0; i < 5; i++ { | |
chanEvent1() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment