thread.go 553 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package util
  2. /**
  3. 线程处理工具类
  4. **/
  5. import (
  6. "sync"
  7. )
  8. type Thead struct {
  9. Size int
  10. pool chan bool
  11. wait *sync.WaitGroup
  12. }
  13. func NewThreads(size int) *Thead {
  14. th := &Thead{size, make(chan bool, size), &sync.WaitGroup{}}
  15. return th
  16. }
  17. func (th *Thead) Open() {
  18. th.pool <- true
  19. th.wait.Add(1)
  20. }
  21. func (th *Thead) Close() {
  22. <-th.pool
  23. th.wait.Add(-1)
  24. }
  25. func (th *Thead) Run(fn func(arg ...any), args ...any) {
  26. th.pool <- true
  27. go func() {
  28. defer func() {
  29. <-th.pool
  30. }()
  31. fn(args...)
  32. }()
  33. }
  34. func (th *Thead) Wait() {
  35. th.wait.Wait()
  36. }