Code Monkey home page Code Monkey logo

async's Introduction

Async

parallel 并发调用

通过信号量控制同一时间的最大并发数量,如果中间有错误产生,则会取消后续排队的任务。

func run() (err error) {
	
	// 生成 runner
	runner := func(index int) parallel.Runner[int] {
		return func(ctx context.Context) (result int, err error) {
			return index, nil
		}
	}
	
	var runners []parallel.Runner[int]
	for i := 0; i < 10000; i++ {
		runners = append(runners, runner(i))
	}
	
	// 同时最多有 10 个并发
	results := parallel.Run[int](context.Background(), 10, runners)
	
	// 固定写法,用于从通道中接收处理结果
	for v := range results {
		if v.Error != nil {
			// 错误处理
		} else {
			// 处理数据
			_ = v.Value
		}
	}
	
	return
}

race 竞赛调用

取最先成功的结果返回,取消或忽略后续排队的任务执行,如果全部任务都失败,则返回合并的错误。

func main() {
	runners := []*race.Runner[int]{
		{
			Delay: 0,
			Runner: func(ctx context.Context) (result int, err error) {
				result = 1
				return
			},
		},
		{
			Delay: 2 * time.Second,
			Runner: func(ctx context.Context) (result int, err error) {
				result = 3
				return
			},
		},
		{
			Delay: 3 * time.Second,
			Runner: func(ctx context.Context) (result int, err error) {
				result = 2
				return
			},
		},
	}
	
	race.Run[int](context.Background(), runners)
}   

async's People

Contributors

hucansen avatar koyeo avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.