func main() {
for i := 0; i < 1000; i++ {
go func(i int) {
for {
fmt.Printf("Hello from goroutine %d\n", i)
}
}(i)
}
time.Sleep(time.Millisecond)
}
协程Coroutine
轻量级线程
非抢占式多任务处理,由协程主动交出控制权
编译器/解释器/虚拟机层面的多任务
多个协程可能在一个或多个线程上运行
手动交出控制权
runtime.Gosched()
检测数据访问的冲突
�go run —race xx.go
goroutine可能的切换点
I/O,select
channel
等待锁
函数调用(有时)
runtime.Gosched()
channel(通道)
不要通过共享内存来通信,通过通信来共享内存
package main
import (
"fmt"
"time"
)
func worker(id int, c chan int) {
for n := range c { // 也可以使用range来检测是否还有值
//n, ok := <-c // 判断发送方是否已关闭
//if !ok {
// break
//}
fmt.Printf("worker %d received %d \n", id, n)
}
}
// chan<- 发数据
// <-chan 收数据
func createWorker(id int) chan<- int {
c := make(chan int)
go func() {
for {
fmt.Printf("worker %d received %c \n", id, <-c)
}
}()
return c
}
func chanDemo() {
var channels [10]chan<- int
for i := 0; i < 10; i++ {
channels[i] = createWorker(i)
}
for i := 0; i < 10; i++ {
channels[i] <- i
}
time.Sleep(time.Millisecond)
}
func bufferedChannel() {
c := make(chan int, 3) // 第二个参数为缓存区
c <- 1
c <- 2
c <- 3
go worker(0, c)
time.Sleep(time.Millisecond)
}
func channelClose() {
c := make(chan int, 3) // 第二个参数为缓存区
c <- 1
c <- 2
c <- 3
go worker(0, c)
close(c)
time.Sleep(time.Millisecond)
}
func main() {
//chanDemo()
//bufferedChannel()
channelClose()
}