-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmatching.go
38 lines (35 loc) · 1 KB
/
matching.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package main
import (
"fmt"
"sync"
)
// This programs demonstrates how a channel can be used for sending and
// receiving by any number of goroutines. It also shows how the select
// statement can be used to choose one out of several communications.
func main() {
people := []string{"Anna", "Bob", "Cody", "Dave", "Eva"}
match := make(chan string, 1) // Make room for one unmatched send.
wg := new(sync.WaitGroup)
wg.Add(len(people))
for _, name := range people {
go Seek(name, match, wg)
}
wg.Wait()
select {
case name := <-match:
fmt.Printf("No one received %s’s message.\n", name)
default:
// There was no pending send operation.
}
}
// Seek either sends or receives, whichever possible, a name on the match
// channel and notifies the wait group when done.
func Seek(name string, match chan string, wg *sync.WaitGroup) {
select {
case peer := <-match:
fmt.Printf("%s sent a message to %s.\n", peer, name)
case match <- name:
// Wait for someone to receive my message.
}
wg.Done()
}