nil:
, , . , .
:
wo.x, wo.y, wo.z = 1,2,3
, wo. ; Work. , .
nil struct nil. struct , nil.
var wo *Work
wo Work nil.
var wo = &Work{}
wo Work Work.
:
wo := &Work{}
:
, . func worker . , .
, , sync.WaitGroup. , , .
waitgroup, goroutines .
wg.Add(3)
:
wg.Wait()
wg.Done()
, .
, , func receiveWork for range. , goroutine :
go func() {
wg.Wait()
close(out)
}()
:
package main
import (
"fmt"
"sync"
"time"
)
type Work struct {
x, y, z int
}
func worker(in <-chan *Work, out chan<- *Work, wg *sync.WaitGroup) {
for w := range in {
w.z = w.x + w.y
time.Sleep(time.Duration(w.z))
out <- w
}
wg.Done()
}
func sendWork(in chan<- *Work) {
wo := &Work{x: 1, y: 2, z: 3}
in <- wo
in <- wo
in <- wo
in <- wo
in <- wo
close(in)
}
func receiveWork(out <-chan *Work) []*Work {
var slice []*Work
for el := range out {
slice = append(slice, el)
}
return slice
}
func main() {
var wg sync.WaitGroup
in, out := make(chan *Work), make(chan *Work)
wg.Add(3)
for i := 0; i < 3; i++ {
go worker(in, out, &wg)
}
go sendWork(in)
go func() {
wg.Wait()
close(out)
}()
data := receiveWork(out)
fmt.Printf("%v", data)
}
:
[0x104382f0 0x104382f0 0x104382f0 0x104382f0 0x104382f0]
, , , . . .
, Work, , :
for _, w := range data {
fmt.Printf("%v", w)
}
:
&{1 2 3}&{1 2 3}&{1 2 3}&{1 2 3}&{1 2 3}
Go , , .
:
*Work , goroutines . , . Work *Work.
, , , Work , , , *Work, goroutine.
, go race detector, :
C:/Go\bin\go.exe run -race C:/gopath/src/github.com/drathier/scratchpad/go/main/main.go
[0xc0820403c0 0xc0820403c0 0xc0820403c0 0xc0820403c0 0xc0820403c0]==================
WARNING: DATA RACE
Write by goroutine 6:
main.worker()
C:/gopath/src/github.com/drathier/scratchpad/go/main/main.go:15 +0x8a
Previous write by goroutine 8:
main.worker()
C:/gopath/src/github.com/drathier/scratchpad/go/main/main.go:15 +0x8a
Goroutine 6 (running) created at:
main.main()
C:/gopath/src/github.com/drathier/scratchpad/go/main/main.go:45 +0x10c
Goroutine 8 (running) created at:
main.main()
C:/gopath/src/github.com/drathier/scratchpad/go/main/main.go:45 +0x10c
==================
Found 1 data race(s)
exit status 66
:
w.z = w.x + w.y
goroutines w.z, , w.z, , . , *Work : Work.