You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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)
}
}
The text was updated successfully, but these errors were encountered:
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)
}
The text was updated successfully, but these errors were encountered: