Queues

CI Go Report Card Go Reference

A simple sync.WaitGroup like queue and goroutine execution controller.

Features

  • Limit maximum goroutine execution/count.
  • Wait for all the goroutines to finish.
  • Run goroutines like a queue batch.

Import

import "github.com/hsblhsn/queues"

Example

🔗 Go Playground: Limit maximum goroutine counts to 3.

package main

import (
	"fmt"
	"time"

	"github.com/hsblhsn/queues"
)

func main() {
	q := queues.New(3)
	for i := 0; i < 30; i++ {
		q.Add(1)
		go func(n int) {
			defer q.Done()
			time.Sleep(time.Second)
			fmt.Println(n)
		}(i)
	}
	q.Wait()
}

🔗 Go Playground: Batched queue for async jobs.

package main

import (
	"fmt"
	"time"

	"github.com/hsblhsn/queues"
)

func main() {
	urls := []string{
		"https://google.com",
		"https://github.com",
		"https://twitter.com",
		"https://facebook.com",
		"https://youtube.com",
	}
	q := queues.New(2)
	for _, v := range urls {
		q.Add(1)
		go crawl(q, v)
	}
	q.Wait()
}

func crawl(q *queues.Q, url string) {
	defer q.Done()
	fmt.Println("Crawling: ", url)
	time.Sleep(time.Second)
}

GitHub

View Github