Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
patrickToca opened this issue Oct 25, 2015 · 0 comments
Open

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

patrickToca opened this issue Oct 25, 2015 · 0 comments

Comments

@patrickToca
Copy link

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)
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant