阻塞在for或者listen上不让go程序立马退出

    技术2022-07-10  90

    package main import ( "fmt" "strconv" "time" ) var exit = make(chan int) var strChan = make(chan string) func main() { i := 0 go func() { for { i++ strChan <- strconv.Itoa(i) time.Sleep(time.Second) } }() go func() { for str := range strChan { fmt.Println(str) } }() // 等待退出 <-exit } /* 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ... */

    由于有代码没执行完毕,比如: 网络监听死循环阻塞在listen上或者本例这样阻塞在for循环上,这样进程才不会退出就不会报: dead的异常

     

    ------------------------------------再比如:阻塞在Listen上不会退出

    main

    package main import "fmt" func main() { // 因为这行,所以服务器不会退出 Listen() queue := NewEventQueue() fmt.Println("StartLoop") queue.StartLoop() fmt.Println("Wait") queue.Wait() fmt.Println("exit") }

    queue

    package main type EventQueue interface { StartLoop() Wait() int } type eventQueue struct { queue chan func() exitSingal chan int } func (q *eventQueue) StartLoop() { go func() { for callback := range q.queue { callback() } }() } func (q *eventQueue) Wait() int { return <-q.exitSingal } func NewEventQueue() EventQueue { return &eventQueue{ queue: make(chan func(), 100), exitSingal: make(chan int), } }

    listen

    package main import ( "fmt" "log" "net" ) func Listen() { listen, err := net.Listen("tcp", "localhost:8000") if err != nil{ log.Fatal(err) } fmt.Println("服务器启动成功!") for{ conn, err := listen.Accept() if err != nil{ log.Println(err) continue } go handleConn(conn) } } func handleConn(conn net.Conn) { }

     

    不阻塞在Listen上则报错

    StartLoop Wait fatal error: all goroutines are asleep - deadlock! goroutine 1 [chan receive]: main.(*eventQueue).Wait(0xc0000383e0, 0xc000006018) E:/workspace/src/TestGo/demo07/queue.go:23 +0x49 main.main() E:/workspace/src/TestGo/demo07/main.go:16 +0x18c goroutine 6 [chan receive]: main.(*eventQueue).StartLoop.func1(0xc0000383e0) E:/workspace/src/TestGo/demo07/queue.go:16 +0x67 created by main.(*eventQueue).StartLoop E:/workspace/src/TestGo/demo07/queue.go:15 +0x46

     

     

    Processed: 0.038, SQL: 9