Skip to content

Commit

Permalink
Separate LenGoroutines into Len and Groutines
Browse files Browse the repository at this point in the history
  • Loading branch information
Tooghi committed Jan 18, 2022
1 parent 387494f commit 2b8fcc8
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 23 deletions.
18 changes: 1 addition & 17 deletions goroutine.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func (g *Goroutine) Start() {
return
case t := <-g.Pipe:
g.SetStatus(Progress)
executeTask(g.ctx, t)
ExecuteTask(g.ctx, t)
g.SetStatus(Idle)
}
}
Expand All @@ -63,19 +63,3 @@ func (g Goroutine) Status() Status {
func (g *Goroutine) Kill() {
g.cnl()
}

func executeTask(ctx context.Context, task Task) {
err := task.execute(ctx)
if err == nil {
if task.success != nil {
task.success()
}
} else {
if task.fail != nil {
task.fail(err)
}
}
if task.final != nil {
task.final()
}
}
20 changes: 14 additions & 6 deletions pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package pooli
import (
"context"
"math"
"sync"
)

type Pool struct {
Expand All @@ -12,7 +11,7 @@ type Pool struct {
goroutines []*Goroutine
pipe chan Task

m *sync.RWMutex
// m *sync.RWMutex
}

func Open(goroutines int) *Pool {
Expand All @@ -30,7 +29,7 @@ func Open(goroutines int) *Pool {
ctx: ctx,
goroutines: grs,
pipe: pipe,
m: new(sync.RWMutex),
// m: new(sync.RWMutex),
}
}

Expand Down Expand Up @@ -64,22 +63,31 @@ func (p *Pool) SetGoroutines(n int) {
n = int(math.Abs(float64(n)))
for i := 0; i < n; i++ {
g := NewGoroutine(p.ctx, p.pipe)
g.Start()
p.goroutines = append(p.goroutines, g)
p.AddGoroutine(g)
}
}
}

func (p *Pool) LenGoroutines() int {
func (p *Pool) Len() int {
return len(p.goroutines)
}

func (p *Pool) Goroutines() []*Goroutine {
return p.goroutines
}

func (p *Pool) AddGoroutine(g *Goroutine) {
g.Start()
p.goroutines = append(p.goroutines, g)
}

func (p *Pool) RemoveGoroutine(g *Goroutine) {
for i, gr := range p.goroutines {
if gr != g {
continue
}

gr.cnl()
p.goroutines = append(p.goroutines[:i], p.goroutines[i+1:]...)
}
}
Expand Down
16 changes: 16 additions & 0 deletions task.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,19 @@ func (t Task) Final(f func()) Task {
t.final = f
return t
}

func ExecuteTask(ctx context.Context, task Task) {
err := task.execute(ctx)
if err == nil {
if task.success != nil {
task.success()
}
} else {
if task.fail != nil {
task.fail(err)
}
}
if task.final != nil {
task.final()
}
}

0 comments on commit 2b8fcc8

Please sign in to comment.