hic003cih / Golang

0 stars 0 forks source link

WaitGroup #38

Open hic003cih opened 4 years ago

hic003cih commented 4 years ago

starting code

package main

import ( "fmt" )

func main() { foo() bar() }

func foo() { for i := 0; i < 10; i++ { fmt.Println("foo:", i) } }

func bar() { for i := 0; i < 10; i++ { fmt.Println("bar:", i) } }

hic003cih commented 4 years ago

package main

import ( "fmt" "runtime" "sync" )

var wg sync.WaitGroup

func main() { fmt.Println("OS\t\t", runtime.GOOS) fmt.Println("ARCH\t\t", runtime.GOARCH) fmt.Println("CPUs\t\t", runtime.NumCPU()) fmt.Println("Goroutines\t", runtime.NumGoroutine())

wg.Add(1)
go foo()
bar()

fmt.Println("CPUs\t\t", runtime.NumCPU())
fmt.Println("Goroutines\t", runtime.NumGoroutine())
wg.Wait()

}

func foo() { for i := 0; i < 10; i++ { fmt.Println("foo:", i) } wg.Done() }

func bar() { for i := 0; i < 10; i++ { fmt.Println("bar:", i) } }

hic003cih commented 4 years ago

Method sets revisited

package main

import ( "fmt" "math" )

type circle struct { radius float64 }

type shape interface { area() float64 }

func (c circle) area() float64 { return math.Pi c.radius * c.radius }

func info(s shape) { fmt.Println("area", s.area()) }

func main() { c := circle{5} // info(c) fmt.Println(c.area()) }

hic003cih commented 4 years ago

Race condition

package main

import ( "fmt" "runtime" "sync" )

func main() { fmt.Println("CPUs:", runtime.NumCPU()) fmt.Println("Goroutines:", runtime.NumGoroutine())

counter := 0

const gs = 100
var wg sync.WaitGroup
wg.Add(gs)

for i := 0; i < gs; i++ {
    go func() {
        v := counter
        // time.Sleep(time.Second)
        runtime.Gosched()
        v++
        counter = v
        wg.Done()
    }()
    fmt.Println("Goroutines:", runtime.NumGoroutine())
}
wg.Wait()
fmt.Println("Goroutines:", runtime.NumGoroutine())
fmt.Println("count:", counter)

}

hic003cih commented 4 years ago

Documentation

package main

import ( "fmt" )

func doSomething(x int) int { return x * 5 }

func main() { ch := make(chan int) go func() { ch <- doSomething(5) }() fmt.Println(<-ch) }