Skip to content

Instantly share code, notes, and snippets.

@onsi
Last active August 29, 2015 14:07
Show Gist options
  • Save onsi/62b363afee6cb160637e to your computer and use it in GitHub Desktop.
Save onsi/62b363afee6cb160637e to your computer and use it in GitHub Desktop.
Go ordered semaphore
package experiments_test
import (
"fmt"
"sync"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Semaphore", func() {
var semaphore chan struct{}
var N, maxConcurrent int
BeforeEach(func() {
N = 1000
maxConcurrent = 20
semaphore = make(chan struct{}, maxConcurrent)
//fill the semaphore
for i := 0; i < maxConcurrent; i++ {
semaphore <- struct{}{}
}
})
It("should unblock goroutines waiting on the semaphore in FIFO order", func() {
results := []int{}
lock := &sync.Mutex{}
wg := &sync.WaitGroup{}
wg.Add(N)
expected := []int{}
//schedule a lot of work
for i := 0; i < N; i++ {
i := i
go func() {
semaphore <- struct{}{}
lock.Lock()
results = append(results, i)
lock.Unlock()
<-semaphore
wg.Done()
}()
time.Sleep(time.Millisecond)
expected = append(expected, i)
}
//start running the work
for i := 0; i < maxConcurrent; i++ {
<-semaphore
}
wg.Wait()
for i := 0; i < len(expected); i++ {
if results[i] != expected[i] {
fmt.Println("MISMATCH:", results[i], expected[i])
}
}
Ω(results).Should(Equal(expected))
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment