内容纲要

[go]
package main

import (
"fmt"
"time"
)

func namedFunction() {
time.Sleep(10000)
fmt.Println("Printing from namedFunction!")
}

func main() {
fmt.Println("Chapter 09 – Goroutines.")

go namedFunction()

go func() {
fmt.Println("An anonymous function!")
}()

time.Sleep(10000)
fmt.Println("Exiting…")
}

[/go]

[code]
Chapter 09 – Goroutines.
An anonymous function!
Printing from namedFunction!
Exiting…
[/code]

[go]
package main

import (
"fmt"
"time"
)

func main() {
fmt.Println("Chapter 09 – Goroutines.")

for i := 0; i < 10; i++ {
go func(x int) {
time.Sleep(10)
fmt.Printf("%d ", x)
}(i)
}

time.Sleep(10000000)
fmt.Println("Exiting…")
}

[/go]

[code]
Chapter 09 – Goroutines.
1 6 9 0 5 4 3 2 8 7 Exiting…
[/code]

等待协程

[go]
package main

import (
"fmt"
"sync"
)

func main() {
fmt.Println("Waiting for Goroutines!")

var waitGroup sync.WaitGroup
waitGroup.Add(10)
var i int64
for i = 0; i < 10; i++ {

go func(x int64) {
defer waitGroup.Done()
fmt.Printf("%d ", x)
}(i)
}

waitGroup.Wait()
fmt.Println("\nExiting…")
}

[/go]

[code]
Waiting for Goroutines!
0 9 6 2 3 4 7 8 5 1
Exiting…
[/code]

发表评论

电子邮件地址不会被公开。 必填项已用*标注