Skip to content

Instantly share code, notes, and snippets.

@bschaeffer
Last active May 9, 2019 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bschaeffer/9c54e799dc455bb25fba5e17e0740807 to your computer and use it in GitHub Desktop.
Save bschaeffer/9c54e799dc455bb25fba5e17e0740807 to your computer and use it in GitHub Desktop.
Shared Request - Shares a single request across multiple go routines
package main
import (
"fmt"
"sync"
"time"
)
type SharedRequest struct {
data string
loading bool
lock sync.Mutex
wg sync.WaitGroup
}
func (r *SharedRequest) Exec() {
r.lock.Lock()
defer r.lock.Unlock()
if !r.loading {
r.loading = true
r.wg.Add(1)
go func() {
time.Sleep(5 * time.Second)
r.wg.Done()
}()
}
}
func (r *SharedRequest) Wait() {
r.wg.Wait()
}
func main() {
req := &SharedRequest{}
req.Wait()
fmt.Println("Done")
start := time.Now()
for i := 0; i < 4; i++ {
req.Exec()
}
time.Sleep(2 * time.Second)
for i := 0; i < 4; i++ {
req.Exec()
}
req.Wait()
duration := time.Since(start)
fmt.Println("Done", duration)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment