Limiting goroutines on a exact time

func Routines(){
    for {
        go JustAnotherFunc()
    }
}

This is my current function looks like, but I want to limit only 100 routines at once, if 1 routine finished another one will run. but the total number of goroutines must be 100

Any way to achieve this?

Try a semaphore.

use go chan, chan is thread safe queue

/*
 * Copyright 2018. bigpigeon. All rights reserved.
 * Use of this source code is governed by a MIT style
 * license that can be found in the LICENSE file.
 */

package main

import (
	"fmt"
	"math/rand"
	"time"
)

type Task time.Duration

func (t Task) Run() {
	fmt.Println("sleep ", time.Duration(t))
	time.Sleep(time.Duration(t))
}

func Work(task Task, token chan struct{}) {
	task.Run()
	<-token
}

// max routines
var MaxRoutines = 100

type Routines struct {
	tokens chan struct{}
}

func (r Routines) Call(task Task) {
	// if routines > MaxRoutine , will block
	r.tokens <- struct{}{}
	go Work(task, r.tokens)
}

func main() {
	routines := Routines{tokens: make(chan struct{}, MaxRoutines)}

	for i := 0; true; i++ {
		task := Task(time.Duration(rand.Intn(10)+1) * time.Second)
		routines.Call(task)
		fmt.Println("n ", i)
	}
}
1 Like
const maxRoutines = 100


func Routines() {
var wg sync.WaitGroup
	for {

		for i := 0; i < 100; i++ {
			wg.Add(1)
			go anotherFunc(wg){
				defer wg.Done()
                                // Do work
			}(wg)
		}
		wg.Wait()

	}

}

Something like this?
But maybe have a look at worker pattern. It may be the thing you are looking for.

Also I want to share something interesting with you.
check this
http://divan.github.io/posts/go_concurrency_visualize/

1 Like