semaphore

package
v1.3.8 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2024 License: Apache-2.0 Imports: 0 Imported by: 24

README

concurrent

concurrent utils for golang

peference

// concurrent.semaphore
BenchmarkSemaphore(TryAcquire()&&Release())				20000000	89.6 ns/op
BenchmarkSemaphoreConcurrent(TryAcquire()&&Release())	20000000	89.9 ns/op
	

usage

package main
import(
    "fmt"
    "time"

    nsema "github.com/niean/gotools/concurrent/semaphore"
)

func main(){
    // init sema
    concurrentNum := 2 // 5,10..
    sema := nsema.NewSemaphore(concurrentNum)

    // use sema
    for i:=0; i<100; i++ {
        go func(num int){
            if !sema.TryAcquire() {
                fmt.Printf("%d, get sema, fail\n", num)
                return
            }
            defer sema.Release()

            time.Sleep(1*time.Nanosecond)
            fmt.Printf("%d, get sema, ok\n", num)
        }(i)
    }

    // keep alive
    time.Sleep(2*time.Second)
}

reference

TODO

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
}

func NewSemaphore

func NewSemaphore(concurrencyNum int) *Semaphore

func (*Semaphore) Acquire

func (this *Semaphore) Acquire()

func (*Semaphore) AvailablePermits

func (this *Semaphore) AvailablePermits() int

func (*Semaphore) Release

func (this *Semaphore) Release()

func (*Semaphore) TryAcquire

func (this *Semaphore) TryAcquire() bool

Jump to

Keyboard shortcuts

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