Skip to content

Instantly share code, notes, and snippets.

@armando-couto
Created March 7, 2022 00:12
Show Gist options
  • Save armando-couto/359c61b4da06f181d703fc9fb792757b to your computer and use it in GitHub Desktop.
Save armando-couto/359c61b4da06f181d703fc9fb792757b to your computer and use it in GitHub Desktop.
Let’s expand on this example and show both sides of the equation: a goroutine that is waiting for a signal, and a goroutine that is sending signals. Say we have a queue of fixed length 2, and 10 items we want to push onto the queue. We want to enqueue items as soon as there is room, so we want to be notified as soon as there’s room in the queue
package main
import (
"fmt"
"sync"
"time"
)
func main() {
c := sync.NewCond(&sync.Mutex{})
queue := make([]interface{}, 0, 10)
removeFromQueue := func(delay time.Duration) {
time.Sleep(delay)
c.L.Lock()
queue = queue[1:]
fmt.Println("Removed from queue")
c.L.Unlock()
c.Signal()
}
for i := 0; i < 10; i++ {
c.L.Lock()
for len(queue) == 2 {
c.Wait()
}
fmt.Println("Adding to queue")
queue = append(queue, struct{}{})
go removeFromQueue(1 * time.Second)
c.L.Unlock()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment