123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- 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
- }
|