sema

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2019 License: Apache-2.0 Imports: 3 Imported by: 1

README

Sema Build Status Go Report Card

Sema is a simple semaphore implementation for Go (golang) to control concurrent access to shared resources. (Go still lacks a user accessible semaphore implementation in the standard library)

Example

Install
go get github.com/brunotm/sema
Usage

package main
import (
	"time"
	"context"
	"github.com/brunotm/sema"
)

func main() {
	max := 100
	s := sema.New(max)

	s.Acquire()
	defer s.Release()
	// DO WORK...

	// OR
	if s.TryAcquire() {
		defer s.Release()
		// DO WORK...
	}

	// OR
	if s.AcquireWithin(5 * time.Millisecond) {
		defer s.Release()
		// DO WORK...
	}

	// OR
	if s.AcquireWith(context.Background()) {
		defer s.Release()
		// DO WORK...
	}

}

Written by Bruno Moura brunotm@gmail.com

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Sema

type Sema chan struct{}

Sema provides a simple semaphore implementation

func New

func New(size int) (s Sema, err error)

New creates a new semaphore with the given maximum capacity for concurrent access.

func (Sema) Acquire

func (s Sema) Acquire()

Acquire will block if semaphore is full until any other holder release it.

func (Sema) AcquireWith added in v0.3.0

func (s Sema) AcquireWith(ctx context.Context) (ok bool)

AcquireWith the given context, will block if semaphore is full until any other holder release or the context is canceled/expired.

func (Sema) AcquireWithin

func (s Sema) AcquireWithin(timeout time.Duration) (ok bool)

AcquireWithin the given timeout return true on success and false on failure

func (Sema) Cap

func (s Sema) Cap() (sinze int)

Cap return semaphore capacity

func (Sema) Holders

func (s Sema) Holders() (count int)

Holders return the current holders count

func (Sema) Release

func (s Sema) Release()

Release the semaphore allowing wating waiters to acquire.

func (Sema) TryAcquire

func (s Sema) TryAcquire() (ok bool)

TryAcquire the semaphore without blocking return true on success and false on failure.

Jump to

Keyboard shortcuts

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