goroutin和channel使用样例

[source lang="c"]

package main

import "fmt"

func sum(values []int, resultChan chan int){
sum := 0
for _, value := range values{
sum += value
}

resultChan <- sum // send result to channel
}

func main(){
values := [] int {1,2,3,4,5,6}

channel_capacity := 2 // capacity 2
resultChan := make(chan int, channel_capacity)

go sum(values[:len(values)/2], resultChan) // 计算前半部分
go sum(values[len(values)/2:], resultChan) // 计算后半部分

sum1, sum2 := <- resultChan, <- resultChan // 从通道中获取计算结果

fmt.Println("Sum: ", sum1, sum2, sum1+sum2)

}

[/source]

另外一个样例:

[source lang="c"]
package main

import (
"fmt"
"time"
"os"
)

func Count(ch chan int) {
ch <- 1
fmt.Println("Counting")
os.Stdout.Sync()
}

func main() {
chs := make([] chan int, 10)

for i := 0; i < 10; i++ {
chs[i] = make(chan int)
go Count(chs[i])
}

for idx, ch := range(chs) {
fmt.Printf("idx %d value %d\n", idx, <-ch)
}

time.Sleep(1000 * time.Millisecond)
fmt.Println("\nAll System Go!")
}
[/source]

发表评论

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