28.蛤蟆笔记go语言——并发简单示例
并发示例
package main
import (
"fmt"
"time"
)
func ready(w string, sec int64) {
secs :=time.Duration(sec) * time.Second
time.Sleep(secs)
fmt.Println(w,"is ready!")
}
func main() {
goready("Tee", 2)
goready("Coffee", 1)
fmt.Println("I'mwaiting")
secs :=time.Duration(2) * time.Second
time.Sleep(5* secs)
}
输出:
I'mwaiting
Coffeeis ready!
Teeis ready!
Go语法特点
没有共享内存,更没有内存锁,并发靠语言自带的 goroutines
goroutines 之间的通信靠语⾔自带的 channels 来传递消息
总之,这⼀切都有利于简单地编写安全的并发程序。
并行计算
代码:
package main
import "fmt"
func sum(values []int, resultChan chan int) {
sum :=0
for _,value := range values {
sum+= value
}
resultChan<- sum // 将计算结果发送到channel中
}
func main() {
values:= []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
resultChan:= make(chan int, 2)
gosum(values[:len(values)/2], resultChan)
gosum(values[len(values)/2:], resultChan)
sum1,sum2 := <-resultChan, <-resultChan // 接收结果
fmt.Println("Result:",sum1, sum2, sum1+sum2)
}
执行结果
Result: 40 15 55
有疑问加站长微信联系(非本文作者)