go 协程池 数量控制

go 协程池

C++/Java基本都有专门的库去实现线程池,而go语言由于有goroutine的存在,并没有提供协程池这样的组件。

自己写了一个控制goroutine数量组件 使用方法很简单

import (
	"fmt"
	"testing"

	"github.com/erdong01/kit/goWorker"
)

func TestWork(t *testing.T) {
	goworker := goWorker.New(16)
	goworker.Go(func() {
		fmt.Println("111")
	})
	goworker.Go(func() {
		fmt.Println("222")
	})

	goworker.Go(func() {
		fmt.Println("333")
	})

	goworker.Go(func() {
		fmt.Println("444")
	})

	goworker.Go(func() {
		fmt.Println("555")
	})
	goworker.Go(func() {
		fmt.Println("555")
	})
	goworker.Go(func() {
		fmt.Println("777")
	})
	goworker.Go(func() {
		fmt.Println("888")
	})
	goworker.Go(func() {
		fmt.Println("999")
	})

	goworker.Wait()
}

go worker实现逻辑

package goWorker

import (
	"fmt"
	"log"
	"runtime/debug"
	"sync"
)

type worker struct {
	// Record the number of running workers
	//协程数量
	workerCount int
	sem         chan struct{}
	wg          sync.WaitGroup
}

func NewWorker(count ...int) (p *worker) {
	p = &worker{}
	p.workerCount = 32
	if len(count) > 0 {
		p.workerCount = count[0]
	}
	p.sem = make(chan struct{}, p.workerCount)
	return p
}

func (that *worker) Go(f func()) {
	that.sem <- struct{}{}
	that.wg.Add(1)
	go func() {
		defer that.wg.Add(-1)
		defer func() { <-that.sem }()
		defer func() {
			if r := recover(); r != nil {
				msg := fmt.Sprintf("GOWorker: panic %s", debug.Stack())
				log.Fatal(msg)
			}
		}()
		f()
	}()
}

func (that *worker) Wait() {
	that.wg.Wait()
}

posted @ 2025-06-23 10:21  耳东01  阅读(4)  评论(0)    收藏  举报