package coroutine

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

type LimitNRoutine struct {
	routineTokens *otherutils.RoutineTokens
}

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

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

		fprocess()
	}()
}
