Record

机会是留给有准备的人

简单版的goroutine pool


package main

import (
    "sync"
    "fmt"
    "time"
)

func main(){
    goPool()
    noPool()
}

type f func()

func worker(){
    fmt.Println("hello pool")
}

//简单版的goroutine pool,核心是启动goroutine,没有及时结束,用channel阻塞
func goPool(){

    start :=time.Now()

    var wg sync.WaitGroup

    //定义一个函数类型的channel
    task := make(chan f , 100)

    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            //从channel循环取出函数
            for f := range task {
               f()  //运行函数
            }

        }()
    }

    //循环的将需要允许的函数写入channel
    for i:=0;i<100;i++  {
        task <- worker
    }

    close(task)
    wg.Wait()
    end :=time.Now()
    fmt.Println(end.Sub(start))

}

func noPool(){

    start :=time.Now()
    var wg sync.WaitGroup

    for i:=0;i<1000000;i++  {
        wg.Add(1)
        go func(){
            defer wg.Done()
            worker()

        }()
    }

    wg.Wait()
    end :=time.Now()
    fmt.Println(end.Sub(start))
}