Skip to content

Latest commit

History

9 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

asyncwork

Execute tasks concurrently in golang.

Install

go get -u github.com/nbys/asyncwork/worker

Prepare the tasks

The task is a function with following signature:

typeTaskFunctionfunc() interface{}

It can be declared like this:

task1:=func() interface{} {
time.Sleep(time.Second*4)
fmt.Println("very slow function")
return"I'm ready"
}

All task have to be collected into the slice:

tasks:= []worker.TaskFunction{task1, task2, task3}

Use context.Context to stop running goroutines

ctx, cancel:=context.WithCancel(context.Background())
defercancel()

Execute the tasks

Start task execution:

resultChannel:=worker.PerformTasks(ctx, tasks)

Get result from completed tasks

Loop over the channel with results.

forresult:=rangeresultChannel {
switchresult.(type) {
caseerror:
fmt.Println("Received error")
cancel()
returncasestring:
fmt.Println("Here is a string:", result.(string))
caseint:
fmt.Println("Here is an integer:", result.(int))
default:
fmt.Println("Some unknown type ")
}
}

About

Run tasks concurrently in golang

Resources

Stars

16 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages