Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
bearaujus committed Oct 14, 2023
0 parents commit 8046fc7
Show file tree
Hide file tree
Showing 8 changed files with 493 additions and 0 deletions.
18 changes: 18 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
**/.DS_Store
.idea
go.work

# Test binary, built with `go test -c`
*.test

# Output of the go coverage tool, specifically when used with LiteIDE
*.out

# Dependency directories (remove the comment below to include it)
# vendor/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 bearaujus

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
146 changes: 146 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
# BWorker - Simple & Efficient Worker Pool Implementation in Go

[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/bearaujus/bjson/blob/master/LICENSE)
[![Go Report Card](https://goreportcard.com/badge/github.com/bearaujus/bworker)](https://goreportcard.com/report/github.com/bearaujus/bworker)

BWorker is a lightweight and easy-to-use Go library that provides a simple and efficient way to execute concurrent tasks. It is designed to be flexible enough to handle a wide range of use cases, from simple tasks such as sending emails to more complex tasks such as processing large datasets.

## Features

- **Concurrency:** BWorker provides a simple way to control the number of concurrent workers in your pool.
- **Job queue:** BWorker allows you to queue jobs to be executed by your workers, and it will automatically manage the execution of those jobs.
- **Error handling:** BWorker provides a way to handle errors that occur during job execution.
- **Job retry**: BWorker can automatically retry jobs that fail, a specified number of times.
- **Shutdown:** BWorker provides a way to gracefully shut down your worker pool.

## Installation

To install BWorker, you can run the following command:

```shell
go get github.com/bearaujus/bjson
```

## Usage

To use BWorker, simply create a new instance of the `BWorker` and specify the number of concurrent workers you want to use. You can then add jobs to the worker pool using the `Do()` method. The worker pool will automatically start processing the jobs in the queue.

When you are finished with your worker pool, you should call the `Shutdown()` method to gracefully shut it down.

### Examples

The following example shows how to use BWorker to execute a simple job:

```go
package main

import (
"errors"
"fmt"

"github.com/bearaujus/bworker"
)

func main() {
// Create a new BWorker instance with 10 concurrent workers and a retry count of 2.
bw := bworker.NewBWorker(10, bworker.WithRetry(2))
defer bw.Shutdown()

// Add a job to the worker pool.
bw.Do(func() error {
fmt.Println("Success without retry")
return nil
})

// Add another job to the worker pool with error.
retried := 0
bw.Do(func() error {
retried++

// Return success on the last attempt
if retried == 3 { // 1 (base) + 2 (retry)
fmt.Println("Success with retry:", retried)
return nil
}

fmt.Println("An error occur:", retried)
return errors.New("an error")
})

// Wait for all jobs to finish executing.
bw.Wait()
}
```
```text
Success without retry
An error occur: 1
An error occur: 2
Success with retry: 3
```

To use the options that BWorker provides, you can pass them to the `NewBWorker()` function. For example, the following code creates a new worker pool with 4 workers and a job buffer of 10:

```go
bw := bworker.NewBWorker(4, bworker.WithJobBuffer(10))
```

The following code creates a new worker pool with 4 workers and a retry count of 3:

```go
bw := bworker.NewBWorker(4, bworker.WithRetry(3))
```

The following code creates a new worker pool with 4 workers and an error variable:

```go
var err error
bw := bworker.NewBWorker(4, bworker.WithError(&err))
```

The following code creates a new worker pool with 4 workers and a slice of error variables:

```go
var errs []error
bw := bworker.NewBWorker(4, bworker.WithErrors(&errs))
```

Once you have created a worker pool with options, you can use it just like a regular worker pool. The following code shows how to submit a task to a worker pool with options:

```go
bw.Do(func() error {
// ...
})
```

The following code shows how to wait for all of the tasks in a worker pool with options to be completed:

```go
bw.Wait()
```

The following code shows how to shutdown a worker pool with options:

```go
bw.Shutdown()
```

You can also use options to combine different features. For example, the following code creates a new worker pool with 4 workers, a job buffer of 10, and a retry count of 3:

```go
bw := bworker.NewBWorker(4, bworker.WithJobBuffer(10), bworker.WithRetry(3))
```

## Options

BWorker provides a number of options that can be used to customize the behavior of the worker pool. These options can be passed to the `NewBWorker()` function.

The following options are currently available:

- **WithJobBuffer:** This option specifies the size of the job buffer. The job buffer is a queue of tasks that are waiting to be executed by a worker.
- **WithRetry:** This option specifies the number of times that a task will be retried if it fails.
- **WithError:** This option specifies a pointer to an error variable. If any of the tasks in the worker pool fail, the error will be stored in this variable.
- **WithErrors:** This option specifies a pointer to a slice of error variables. If any of the tasks in the worker pool fail, the errors will be stored in this slice.

## License

This project is licensed under the MIT License - see the LICENSE file for details.
138 changes: 138 additions & 0 deletions bworker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
package bworker

import (
"sync"
)

type BWorker interface {
// Do submit a job to be executed by a worker.
Do(job Job)

// Wait for all jobs to be completed.
Wait()

// Shutdown shut down the worker pool.
Shutdown()

// ResetErr reset the error variable when you are using option WithError.
ResetErr()

// ResetErrs reset the slice of error variables when you are using option WithErrors.
ResetErrs()
}

type bWorker struct {
wg *sync.WaitGroup
mu *sync.Mutex
jobWG *sync.WaitGroup
jobs chan Job

optJobBuffer int
optRetry int
optErr *error
optErrs *[]error

shutdown bool
}

// Job represent a function to be executed by a worker.
type Job func() error

// NewBWorker creates a new worker pool with the specified concurrency level and Option(s).
func NewBWorker(concurrency int, opts ...Option) BWorker {
bw := bWorker{
wg: &sync.WaitGroup{},
mu: &sync.Mutex{},
jobWG: &sync.WaitGroup{},
}
for _, opt := range opts {
opt.Apply(&bw)
}
bw.jobs = make(chan Job, bw.optJobBuffer)
bw.startWorkers(concurrency)
return &bw
}

func (bw *bWorker) startWorkers(numWorkers int) {
if numWorkers <= 0 {
numWorkers = 1
}
bw.wg.Add(numWorkers)
for i := 0; i < numWorkers; i++ {
go bw.startWorker()
}
}

func (bw *bWorker) startWorker() {
defer bw.wg.Done()
for job := range bw.jobs {
bw.execute(job)
}
}

func (bw *bWorker) execute(job Job) {
defer bw.jobWG.Done()
attempts := 1 + bw.optRetry
for attempt := 0; attempt < attempts; attempt++ {
err := job()
if err == nil {
return
}
if attempt != attempts-1 {
continue
}
if bw.optErr != nil {
bw.mu.Lock()
*bw.optErr = err
bw.mu.Unlock()
}
if bw.optErrs != nil {
bw.mu.Lock()
*bw.optErrs = append(*bw.optErrs, err)
bw.mu.Unlock()
}
}
}

func (bw *bWorker) Do(job Job) {
if job == nil || bw.shutdown {
return
}
bw.jobWG.Add(1)
bw.jobs <- job
}

func (bw *bWorker) Wait() {
if bw.shutdown {
return
}
bw.jobWG.Wait()
}

func (bw *bWorker) Shutdown() {
if bw.shutdown {
return
}
bw.shutdown = true
close(bw.jobs)
bw.jobWG.Wait()
bw.wg.Wait()
}

func (bw *bWorker) ResetErr() {
if bw.optErr == nil {
return
}
bw.mu.Lock()
*bw.optErr = nil
bw.mu.Unlock()
}

func (bw *bWorker) ResetErrs() {
if bw.optErrs == nil {
return
}
bw.mu.Lock()
*bw.optErrs = nil
bw.mu.Unlock()
}
Loading

0 comments on commit 8046fc7

Please sign in to comment.