fslimiter

package
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: May 7, 2023 License: MIT Imports: 2 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Concurrency

type Concurrency struct {

	// Max 最大并发度。若值 <1,则无限制
	Max int
	// contains filtered or unexported fields
}

Concurrency 并发度限制器

func (*Concurrency) Wait

func (c *Concurrency) Wait() func()

Wait 获取令牌

返回的 func() 类型的值用于释放锁

Example
package main

import (
	"log"
	"sync"

	"github.com/fsgo/fsgo/fslimiter"
)

func main() {
	limiter := fslimiter.Concurrency{
		Max: 2, // 限制最大并发为 2
	}
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()

			// 从并发限制器获取令牌
			release := limiter.Wait()
			defer release() // 释放令牌

			log.Println("id=", id)
		}(i)
	}
	wg.Wait()
}
Output:

func (*Concurrency) WaitContext

func (c *Concurrency) WaitContext(ctx context.Context) (func(), error)

WaitContext 获取令牌,若失败会返回 error

返回的 第一个func() 类型的值用于释放锁

Jump to

Keyboard shortcuts

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