package coroutine

import (
	"leafstalk/log"
	"leafstalk/otherutils"
)

type LimitNRoutine struct {
	routineTokens otherutils.RoutineTokens
}

func NewLimitNRoutine(routineNum int) *LimitNRoutine {
	lr := new(LimitNRoutine)
	lr.routineTokens.Init(routineNum)
	return lr
}

// 协程加载
func (r *LimitNRoutine) Go(fprocess func()) {
	go func() {
		r.routineTokens.Get()
		defer func() {
			r.routineTokens.Release()
			err := recover()
			if err != nil {
				log.Errorf("Go run error: %s", err)
			}
		}()

		fprocess()
	}()
}
