-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactor reader/writer worker pools (#154)
These were previously stored in raw slices. Now they are stored within the workerPool abstraction. This couples the ability to create a new worker with the pool, making growing and shrinking the number of workers easy. Support w/W keys for increasing/decreasing workers If this needs to be more granular then we can split this to different keys for changing the size of each of the 3 pools separately.
- Loading branch information
1 parent
0da203b
commit 276c407
Showing
2 changed files
with
66 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package main | ||
|
||
import "context" | ||
|
||
type worker interface { | ||
Run(ctx context.Context) | ||
Kill() | ||
} | ||
|
||
func newWorkerPool(factory func() worker) workerPool { | ||
workers := make([]worker, 0) | ||
pool := workerPool{ | ||
workers: workers, | ||
factory: factory, | ||
} | ||
return pool | ||
} | ||
|
||
// workerPool contains a collection of _running_ workers. | ||
type workerPool struct { | ||
workers []worker | ||
factory func() worker | ||
} | ||
|
||
func (p *workerPool) Grow(ctx context.Context) { | ||
w := p.factory() | ||
p.workers = append(p.workers, w) | ||
go w.Run(ctx) | ||
} | ||
|
||
func (p *workerPool) Shrink(ctx context.Context) { | ||
if len(p.workers) == 0 { | ||
return | ||
} | ||
w := p.workers[len(p.workers)-1] | ||
p.workers = p.workers[:len(p.workers)-1] | ||
w.Kill() | ||
} |