Skip to content

Answer to my previous question. The correct version here. #2

Description

@patrickToca

countingSemaphore example (corrected version - #should close issue #1):

package main

import (
"fmt"
"time"
"github.com/robryk/semaphore"
)

var (
// max number of goroutines launched concurrently
MaxOutstanding int = 4
// a list to process
list = []int{}
)

func main() {
for i := 1; i <= 10; i++ {
list = append(list, i)
}
Serve(list)
}

// A throttle limiting the number of goroutines started concurrently
// Comment the line with 's.Release(1) and observe the result.
//
func Serve(queue []int) {
// the initial state of s the semaphore is defining the maximum
// goroutines to be started concurrently: the throttle.
//
s := semaphore.New(MaxOutstanding)
msg := make(chan string)

// start n goroutines until the s.Acquire() blocks
//

for i, item := range queue {
    go func(i, item int) {
        // will not block as long s > 0, 
        // will be released when another goroutine terminates
        s.Acquire(1)
        // any processing here
        text := fmt.Sprintf("from goroutine[%d]= %d\n", i, item)
        msg <- text
        // When done; enable another goroutine to run, increase s.
        s.Release(1)
    }(i, item)
}
for x := 0; x < len(list); x++ {
    fmt.Printf(<-msg)
}

}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions