goroutine

package module
v0.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 6, 2021 License: MIT Imports: 1 Imported by: 0

README

goroutine

Go Report Card GitHub go.mod Go version GitHub

A goroutine wrapper for creating and running panic safe goroutines.

The purpose of this package is to provide a simple wrapper function for goroutines, which automatically handles panics in goroutines. Starting a new goroutine without taking care of recovering from a possible panic in that goroutine itself could crash the whole application.

The Go function runs an arbitrary function f in a separate goroutine, which handles the recovering from panic within that goroutine.

Installation

go get -u github.com/sknr/Goroutine

Usage (with dot import)

Instead of running

go func() {
    panic("Panic raised in Goroutine")
}()

simply call

Go(func() {
    panic("Panic raised in Goroutine")
})

in order to create a panic safe goroutine.

Functions with multiple input params must be wrapped within an anonymous function.

Instead of running

go func(a, b int) {
    panic(a+b)
}(21,21)

simply call

Go(func() {
    func(a, b int) {
        panic(a+b)
    }(21,21)
})

Examples

package main

import (
    "fmt"
    "github.com/sknr/goroutine"
    "log"
)

func init() {
    // Override the default recover function.
    goroutine.SetDefaultRecoverFunc(func(v interface{}, done chan<- error) {
        log.Printf("%v", v)
        done <- fmt.Errorf("panic in goroutine successfully recovered")
    })
}

func main() {
    for i := -3; i <= 3; i++ {
        err := <-goroutine.Go(func() {
            func(a, b int) {
                log.Println(a, "/", b, "=", a/b)
            }(10, i)
        })
        if err != nil {
            log.Println(err)
        }
    }
}
Set a new default recover function

In order to override the default recover function for new goroutines (created with Go(func()) or New(func())), simply set a custom recover function of type RecoverFunc with SetDefaultRecoverFunc

Create a new Goroutine instance with a custom recover function

If you need different recover functions for different goroutines, you can simply call

goroutine.New(func() {
    func(name string) {
        panic(fmt.Sprintln("Hallo", name))
    }("Welt")
}).WithRecoverFunc(func(v interface{}, done chan<- error) {
    log.Printf("Custom recover function in Goroutine, with error: %v", v)
}).Go()

Documentation

Overview

Package Goroutine provides a small wrapper around go's goroutines, in order to easily create panic safe goroutines. Starting a new goroutine without taking care of recovering from a possible panic in that goroutine itself could crash the whole application. Therefore, in case of a panic, triggered by the goroutine which was created by the Go method, the panic will be automatically recovered and the error will be notified via the done channel.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrPanicRecovered is returned when a goroutine has panicked.
	ErrPanicRecovered = &panicError{message: "panic in goroutine recovered", value: nil}

	// ErrRecoverFuncPanicRecovered is returned when the recover function of a goroutine has panicked.
	ErrRecoverFuncPanicRecovered = &panicError{message: "panic in recover function of goroutine recovered", value: nil}
)

Functions

func Go

func Go(f func()) <-chan error

Go runs a function f in a separate goroutine, which does automatically handle the recovering from a panic within that goroutine.

Example
package main

import (
	"fmt"
	"github.com/sknr/goroutine"
)

func main() {
	// Instead of
	go func() {
		values := [3]int{1, 2, 3}
		for i := 0; i < 4; i++ {
			fmt.Println(values[i])
		}
	}()

	// simply call
	goroutine.Go(func() {
		values := [3]int{1, 2, 3}
		for i := 0; i < 4; i++ {
			fmt.Println(values[i])
		}
	})
}
Example (WithInputParam)
package main

import (
	"github.com/sknr/goroutine"
)

func main() {
	// Functions with input params need to be wrapped by an anonymous function.

	// Instead of
	go func(s string) {
		panic(s)
	}("Hello World")

	// simply call
	goroutine.Go(func() {
		func(s string) {
			panic(s)
		}("Hello World")
	})
}

func SetDefaultRecoverFunc

func SetDefaultRecoverFunc(rf RecoverFunc)

SetDefaultRecoverFunc can be used to override the defaultRecoverFunc which is used by Go method.

Note: If you pass nil as a RecoverFunc, the panic will be silently recovered.

Types

type Goroutine

type Goroutine struct {
	// contains filtered or unexported fields
}

Goroutine type contains the function f to run within that goroutine and the recover function rf. The recover function rf will be called in case of a panic in f within that goroutine.

func New added in v0.4.1

func New(f func()) *Goroutine

New creates a new panic safe Goroutine, with the defaultRecoverFunc as recover function.

Example
package main

import (
	"fmt"
	"github.com/sknr/goroutine"
)

func main() {
	err := <-goroutine.New(func() {
		values := [3]int{1, 2, 3}
		for i := 0; i < 4; i++ {
			fmt.Println(values[i])
		}
	}).Go()

	fmt.Println(err)
}
Output:

1
2
3
panic in goroutine recovered: runtime error: index out of range [3] with length 3

func (*Goroutine) Go added in v0.4.1

func (g *Goroutine) Go() <-chan error

The Go method starts a new goroutine which is panic safe. A possible panic will be recovered by the recover function, either set by SetDefaultRecoverFunc or WithRecover.

func (*Goroutine) WithRecover added in v0.4.1

func (g *Goroutine) WithRecover(rf RecoverFunc) *Goroutine

WithRecover overrides the default recover function with rf.

Note: If you pass nil as a RecoverFunc, the panic will be silently recovered.
Example
package main

import (
	"fmt"
	"github.com/sknr/goroutine"
)

func main() {
	err := <-goroutine.New(func() {
		values := [3]int{1, 2, 3}
		for i := 0; i < 4; i++ {
			fmt.Println(values[i])
		}
	}).WithRecover(func(v interface{}, done chan<- error) {
		if err, ok := v.(error); ok {
			done <- err
			return
		}
		done <- fmt.Errorf("recovered: %v", v)
	}).Go()
	fmt.Println(err)
}
Output:

1
2
3
runtime error: index out of range [3] with length 3

type RecoverFunc

type RecoverFunc func(v interface{}, done chan<- error)

The RecoverFunc type defines the signature of a recover function within a Goroutine.

func GetDefaultRecoverFunc

func GetDefaultRecoverFunc() RecoverFunc

GetDefaultRecoverFunc returns the current default recover function for goroutines used by the Go method.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL