You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
thread/thread.go

52 lines
877 B

package thread
import (
"context"
"git.rinsvent.ru/rinsvent/gol"
"sync/atomic"
)
type Manager struct {
Count int32
runningCount atomic.Int32
stop bool
stopped chan bool
}
func (m *Manager) Start(f func()) {
m.stopped = make(chan bool, 1)
for {
if m.stop {
if m.runningCount.Load() < 1 {
gol.Debug("thread manager stopped")
m.stopped <- true
break
}
gol.Debug("thread manager stopping")
continue
}
if m.runningCount.Load() >= m.Count {
continue
}
if m.runningCount.Add(1) > m.Count {
m.runningCount.Add(-1)
gol.Debug("thread manager atomic skip")
continue
}
go func() {
defer m.runningCount.Add(-1)
f()
}()
}
}
func (m *Manager) Wait(ctx context.Context) {
<-ctx.Done()
m.stop = true
gol.Debug("thread manager wait stopped")
<-m.stopped
gol.Debug("thread manager wait break")
}