semaphore

package module
v0.0.0-...-9e2c450 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2022 License: MIT Imports: 3 Imported by: 0

README ¶

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)
}

Documentation ¶

Index ¶

Constants ¶

This section is empty.

Variables ¶

This section is empty.

Functions ¶

This section is empty.

Types ¶

type Semaphore ¶

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

Semaphore is an implementation of weighted semaphore. Uses `golang.org/x/sync/semaphore` under the hood.

func New ¶

func New(max int64) *Semaphore

New returns a new Semaphore with the given max weight.

func (*Semaphore) Add ¶

func (s *Semaphore) Add(ctx context.Context, n int64) error

Add acquires the semaphore with a weight of n

func (*Semaphore) Done ¶

func (s *Semaphore) Done()

Done releases the semaphore with a weight of 1.

func (*Semaphore) DoneN ¶

func (s *Semaphore) DoneN(n int64)

DoneN releases the semaphore with a weight of n.

func (*Semaphore) Exit ¶

func (s *Semaphore) Exit()

Exit calls s.Done() first then calls runtime.Goexit(). If called inside a goroutine, the goroutine will exit immediately. See https://golang.org/pkg/runtime/#Goexit for the documentation.

func (*Semaphore) Wait ¶

func (s *Semaphore) Wait(ctx context.Context) error

Wait for the semaphore to be released.

Jump to

Keyboard shortcuts

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