go sync.pool

package main

import (
    "fmt"
    "runtime"
    "strconv"
    "strings"
    "sync"
    "time"
)

//var gidBufPrefix = []byte("goroutine ")

func main() {

    var funcLst []func()
    for i:=0;i<10;i++{
        //i := i
        f := func() {
            //fmt.Println(i)
        }
        funcLst = append(funcLst, f)
    }

    pol := NewPool(5)
    pol.Gogo(funcLst...)
    time.Sleep(time.Second * 100)
}

type SelfPool struct {
    Pool sync.Pool
    Size int
    Closed bool
}

func NewPool(size int) *SelfPool {
    return &SelfPool{
        Pool: sync.Pool{
            New: func() interface{}{
                return func(f func()) {
                    go func() {
                        fmt.Println("id: ", GoID())
                        f()
                    }()
                }
            },
        },
        Size: size,
    }
}

func (sp *SelfPool) Gogo(fc ...func()) {

    if len(fc) <= 0 {
        return
    }

    for _, f := range fc {
START:
        if f == nil {
            continue
        }

        if sp.Size <= 0 {
            goto START;
        }

        sp.gogo(f)
    }
}

func (sp *SelfPool) gogo(x func()) {
    goObserve := sp.Pool.Get().(func(f func()))
    defer sp.release(goObserve)
    goObserve(x)
    sp.Size --
}

func (sp *SelfPool) release(x func(f func())) {
    sp.Pool.Put(x)
    sp.Size ++
}


func GoID() int {
    var buf [64]byte
    n := runtime.Stack(buf[:], false)
    // 得到id字符串
    idField := strings.Fields(strings.TrimPrefix(string(buf[:n]), "goroutine "))[0]
    id, err := strconv.Atoi(idField)
    if err != nil {
        panic(fmt.Sprintf("cannot get goroutine id: %v", err))
    }
    return id
}

 

posted @ 2022-04-11 18:41  Black_Climber  阅读(51)  评论(0编辑  收藏  举报