(1)java 里的 Thread 默认为 1M,Groutine 的 Stack 初始化为 2K(2)一个 thread 对应一个 kernel space,groutine 则是多对多
for i := 0; i < 10; i++ {go func(i int) {println(i)
}(i)
}
}
func TestGroutine1(t *testing.T) {
count := 0
mutex := sync.Mutex{}
for i := 0; i < 10; i++ {go func() {defer func() {mutex.Unlock()
}()
mutex.Lock()
count++
println(count)
}()}
}
func TestGroutine1(t *testing.T) {
count := 0
mutex := sync.Mutex{}
wg := sync.WaitGroup{}
for i := 0; i < 10; i++ {wg.Add(1)
go func() {defer func() {mutex.Unlock()
}()
mutex.Lock()
count++
println(count)
wg.Done()}()}
wg.Wait()
println("done")
}
联合一个前端开发的场景,应用 ajax 异步去数据
会阻塞在取数据的 channel 上
func AsyncAJAX() chan string {channel := make(chan string)
data := "Hello world"
go func() {time.Sleep(time.Second * 10)
println("ajax 执行结束")
channel <- data
}()
return channel
}
func TestCSP(t *testing.T) {println("Ajax 发送申请")
c := AsyncAJAX()
println("渲染")
println("取数据",<-c)
}
func TestCSP(t *testing.T) {println("Ajax 发送申请")
c := AsyncAJAX()
select {
case ret := <-c:
t.Log(ret)
case <- time.After(time.Second * 5):
t.Log("time out")
}
}
func dataSend(c chan int) {go func() {
for i := 0;;i++ {time.Sleep(time.Second * 1)
println("发送第", i)
c <- i
}}()}
func dataRecv(c chan int) {go func() {
for {time.Sleep(time.Second * 5)
println("接管第", <- c)
}}()}
func TestMore(t *testing.T) {c := make(chan int, 5)
dataSend(c)
dataRecv(c)
time.Sleep(time.Second * 100)
}