tasklane

package
v1.3.4 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2023 License: MIT Imports: 5 Imported by: 1

Documentation

Overview

Package tasklane creates multiple goroutines to wait and run tasks.

TaskLane  := []TaskQueue
TaskQueue := {
  Buffered Channel
  Blocking Channel
  Goroutine Worker
}
Example
package main

import (
	"context"
	"fmt"
	"strconv"
	"sync"

	"github.com/whoisnian/glb/tasklane"
)

type ExampleTask struct {
	wg      *sync.WaitGroup
	content string
}

func (task *ExampleTask) Start() {
	defer task.wg.Done()
	fmt.Println(task.content)
}

func main() {
	wg := new(sync.WaitGroup)
	tl := tasklane.New(context.Background(), 2, 2)

	index := tl.ShortestQueueIndex()
	taskCnt := 10
	wg.Add(taskCnt)
	for i := 0; i < taskCnt; i++ {
		if err := tl.PushTask(&ExampleTask{wg, "start task " + strconv.Itoa(i)}, index); err != nil {
			panic(err)
		}
	}
	wg.Wait()

}
Output:

start task 0
start task 1
start task 2
start task 3
start task 4
start task 5
start task 6
start task 7
start task 8
start task 9

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrTimeout = errors.New("timeout")
)

Functions

This section is empty.

Types

type LaneStatus

type LaneStatus struct {
	LaneSize    int
	QueueSize   int
	PendingTask int
	LastPanic   any
}

type Task

type Task interface {
	Start()
}

type TaskLane

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

func New

func New(ctx context.Context, laneSize, queueSize int) *TaskLane

func (*TaskLane) PushTask

func (tl *TaskLane) PushTask(task Task, index int) error

PushTask will push task to BufferedChannel of specified TaskQueue.

PushTask returns a non-nil error if failed to push task: context.Canceled or context.DeadlineExceeded if the context was Done. tasklane.ErrTimeout if specified TaskQueue is full until timeout.

func (*TaskLane) SetTimeout added in v1.0.0

func (tl *TaskLane) SetTimeout(t time.Duration)

SetTimeout sets the timeout for PushTask(). The default timeout is 1 second.

func (*TaskLane) ShortestQueueIndex

func (tl *TaskLane) ShortestQueueIndex() int

ShortestQueueIndex returns the index of shortest TaskQueue.

func (*TaskLane) Status

func (tl *TaskLane) Status() *LaneStatus

Status returns the status of TaskLane.

func (*TaskLane) Wait added in v1.0.0

func (tl *TaskLane) Wait()

Wait blocks until all TaskQueue ended.

TaskQueue will start exiting if the context was Done. Pending tasks will be aborted.

Jump to

Keyboard shortcuts

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