chan的危险
channelGogoroutinechannelgoroutinechannelgoroutinegoroutinechannelgoroutine
package ct
import (
"fmt"
"testing"
)
func Run(channel chan int) {
defer func() {
fmt.Printf("end ....\n")
}()
lable:
v, _ := <-channel
if v == 0 {
return
} else {
goto lable
}
}
func TestChan3(t *testing.T) {
var channel chan int = make(chan int, 10)
for index := 0; index < 15; index++ {
go Run(channel)
}
for index := 0; index < 10; index++ {
channel <- 0
}
}
复制代码
channel0goroutineforRungoroutineforgoroutineforRungoroutinegoroutine
chan有界,越界必阻
channelmakechannelchannelchannelgoroutinegoroutinechannel
package ct
import (
"fmt"
"testing"
)
func goSend(msgChan chan int) {
for index := 0; index < 100; index++ {
fmt.Printf("send: %v\n", index)
msgChan <- index
}
}
func goRevice(msgChan chan int) {
v, _ := <-msgChan
fmt.Printf("revice: %v\n", v)
}
func TestChan(t *testing.T) {
msgChan := make(chan int, 1)
go goRevice(msgChan)
goSend(msgChan)
}
复制代码
这个代码的输出结果为:
send: 0
send: 1
revice: 0
send: 2
Tests timed out after 60000 ms
复制代码
channel1goRevicegoroutinechannelgoSendsend 00send 1channelgoSendgoRevicechannelrevice: 0goSend1goRevicechannel1goSendsend: 2Tests timed out
循环中使用defer
10deferpanicfordefer
import (
"errors"
"fmt"
"testing"
"time"
)
func CreateError() {
panic(errors.New("error"))
}
func TestDefer(t *testing.T) {
var msgs []string = make([]string, 3)
msgs[0] = "wu"
msgs[1] = "jiu"
msgs[2] = "ye"
for _, message := range msgs {
defer func(msg string) {
fmt.Printf("=====> do defer, by %s ...\n", msg)
if err := recover(); err != nil {
fmt.Println(err)
}
}(message)
CreateError()
}
}
复制代码
deferfortryfinallyforfor
deferdeferdefer
func TestDefer(t *testing.T) {
var msgs []string = make([]string, 3)
msgs[0] = "wu"
msgs[1] = "jiu"
msgs[2] = "ye"
defer func() {
fmt.Printf("end .....\n")
}()
defer func() {
fmt.Printf("end2 ....\n")
}()
for _, message := range msgs {
if message == "ye" {
CreateError()
}
}
defer func() {
fmt.Printf("end3 ....\n")
}()
}
复制代码
上面程序输出结果如下:
end2 ....
end ....
复制代码