package otherutils

import "log"

type RoutineTokens struct {
	semaRoutine chan struct{}
}

func NewRoutineTokens(tokenNum int) *RoutineTokens {
	if tokenNum <= 0 {
		tokenNum = 1
	}

	rt := new(RoutineTokens)
	rt.semaRoutine = make(chan struct{}, tokenNum)
	return rt
}

// Init和NewRoutineTokens只用调用一个
func (m *RoutineTokens) Init(tokenNum int) {
	if tokenNum <= 0 {
		tokenNum = 1
	}
	m.semaRoutine = make(chan struct{}, tokenNum)
}

func (m *RoutineTokens) Acquire() {
	if m.semaRoutine == nil {
		log.Panic("RoutineTokens chan not init")
		return
	}
	m.semaRoutine <- struct{}{}
}

func (m *RoutineTokens) TryAcquire() bool {
	if m.semaRoutine == nil {
		log.Panic("RoutineTokens chan not init")
		return false
	}
	select {
	case m.semaRoutine <- struct{}{}:
		return true
	default:
		return false
	}
}

// 准备废弃
func (m *RoutineTokens) Get() {
	if m.semaRoutine == nil {
		log.Panic("RoutineTokens chan not init")
		return
	}
	m.semaRoutine <- struct{}{}
}

func (m *RoutineTokens) Release() {
	if m.semaRoutine == nil {
		log.Panic("RoutineTokens chan not init")
		return
	}
	<-m.semaRoutine
}
